Commit 0647852c authored by Alexander Butenko's avatar Alexander Butenko

insert/update Functions calls draft

Added count variable which stores returned rows count

Some readme improvements

Allow to pass bind variables for func()

More real example of func
parent f171a2cd
......@@ -68,6 +68,12 @@ class MysqliDb
* @var array
*/
protected $_bindParams = array(''); // Create the empty 0 index
/**
* Variable which holds an amount of returned rows during get/getOne/select queries
*
* @var string
*/
public $count = 0;
/**
* @param string $host
......@@ -118,6 +124,7 @@ class MysqliDb
$this->_query = null;
$this->_whereTypeList = null;
$this->_paramTypeList = null;
$this->count = 0;
}
/**
......@@ -422,12 +429,26 @@ class MysqliDb
$pos = strpos($this->_query, 'UPDATE');
if ($pos !== false) {
foreach ($tableData as $prop => $value) {
if (is_array($value)) {
$this->_query .= $prop ." = ";
if (!empty($value['[I]']))
$this->_query .= $prop . $value['[I]'] . ", ";
else {
$this->_query .= $value['[F]'][0] . ", ";
if (is_array ($value['[F]'][1])) {
foreach ($value['[F]'][1] as $key => $val) {
$this->_paramTypeList .= $this->_determineType($val);
}
}
}
} else {
// determines what data type the item is, for binding purposes.
$this->_paramTypeList .= $this->_determineType($value);
// prepares the reset of the SQL query.
$this->_query .= ($prop . ' = ?, ');
}
}
$this->_query = rtrim($this->_query, ', ');
}
}
......@@ -498,19 +519,28 @@ class MysqliDb
//is insert statement
$keys = array_keys($tableData);
$values = array_values($tableData);
$num = count($keys);
// wrap values in quotes
$this->_query .= '(' . implode($keys, ', ') . ')';
$this->_query .= ' VALUES(';
// wrap values in quotes if needed
foreach ($values as $key => $val) {
$values[$key] = "'{$val}'";
$this->_paramTypeList .= $this->_determineType($val);
if (is_array($val)) {
if (!empty($val['[I]']))
$this->_query .= $keys[$key].$val['[I]'].", ";
else {
$this->_query .= $val['[F]'][0].", ";
if (is_array ($val['[F]'][1])) {
foreach ($val['[F]'][1] as $key => $value) {
$this->_paramTypeList .= $this->_determineType($value);
}
}
}
continue;
}
$this->_query .= '(' . implode($keys, ', ') . ')';
$this->_query .= ' VALUES(';
while ($num !== 0) {
$values[$key] = "'{$val}'";
$this->_paramTypeList .= $this->_determineType($val);
$this->_query .= '?, ';
$num--;
}
$this->_query = rtrim($this->_query, ', ');
$this->_query .= ')';
......@@ -529,7 +559,15 @@ class MysqliDb
if ($hasTableData) {
$this->_bindParams[0] = $this->_paramTypeList;
foreach ($tableData as $prop => $val) {
if (!is_array($tableData[$prop])) {
array_push($this->_bindParams, $tableData[$prop]);
continue;
}
if (is_array($tableData[$prop]['[F]'][1])) {
foreach ($tableData[$prop]['[F]'][1] as $val)
array_push($this->_bindParams, $val);
}
}
}
// Prepare where condition bind parameters
......@@ -600,6 +638,8 @@ class MysqliDb
}
array_push($results, $x);
}
$this->count = $stmt->num_rows;
return $results;
}
......@@ -652,4 +692,72 @@ class MysqliDb
return $this->_mysqli->error;
}
/* Helper functions */
/**
* Method returns generated interval function as a string
*
* @param string interval in the formats:
* "1", "-1d" or "- 1 day" -- For interval - 1 day
* Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear
* Default null;
* @param string Initial date
*
* @return string
*/
public function interval ($diff, $func = "NOW()") {
$types = Array ("s" => "second", "m" => "minute", "h" => "hour", "d" => "day", "M" => "month", "Y" => "year");
$incr = '+';
$items = '';
$type = 'd';
if ($diff && preg_match('/([+-]?) ?([0-9]+) ?([a-zA-Z]?)/',$diff, $matches)) {
if (!empty ($matches[1])) $incr = $matches[1];
if (!empty ($matches[2])) $items = $matches[2];
if (!empty ($matches[3])) $type = $matches[3];
if (!in_array($type, array_keys($types)))
trigger_error ("invalid interval type in '{$diff}'");
$func .= " ".$incr ." interval ". $items ." ".$types[$type] . " ";
}
return $func;
}
/**
* Method returns generated interval function as an insert/update function
*
* @param string interval in the formats:
* "1", "-1d" or "- 1 day" -- For interval - 1 day
* Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear
* Default null;
* @param string Initial date
*
* @return array
*/
public function now ($diff = null, $func = "NOW()") {
return Array ("[F]" => Array($this->interval($diff, $func)));
}
/**
* Method generates incremental function call
* @param int increment amount. 1 by default
*/
public function inc($num = 1) {
return Array ("[I]" => "+" . (int)$num);
}
/**
* Method generates decrimental function call
* @param int increment amount. 1 by default
*/
public function dec ($num = 1) {
return Array ("[I]" => "-" . (int)$num);
}
/**
* Method generates user defined function call
* @param string user function body
*/
public function func ($expr, $bindParams = null) {
return Array ("[F]" => Array($expr, $bindParams));
}
} // END class
......@@ -13,12 +13,30 @@ $db = new Mysqlidb('host', 'username', 'password', 'databaseName');
Next, prepare your data, and call the necessary methods.
### Insert Query
Simple example
```php
$data = Array ("login" => "admin",
"firstName" => "John",
"lastName" => 'Doe'
)
$id = $db->insert('users', $data)
if($id)
echo 'user was created. Id='.$id;
```
Insert with functions use
```php
$data = array(
$data = Array(
'login' => 'admin',
'firstName' => 'John',
'lastName' => 'Doe',
'password' => $db->func('SHA1(?)',Array ("secretpassword+salt")),
// password = SHA1('secretpassword+salt')
'createdAt' => $db->now(),
// createdAt = NOW()
'expires' => $db->now('+1Y')
// expires = NOW() + interval 1 year
// Supported intervals [s]econd, [m]inute, [h]hour, [d]day, [M]onth, [Y]ear
);
$id = $db->insert('users', $data)
......@@ -26,11 +44,24 @@ if($id)
echo 'user was created. Id='.$id;
```
### Select Query
### Update Query
```php
$data = Array (
'firstName' => 'Bobby',
'lastName' => 'Tables',
'editCount' => $db->inc(2)
// editCount = editCount + 2;
);
$db->where('id', 1);
if($db->update('users', $data)) echo 'successfully updated';
```
### Select Query
After any select/get function calls amount or returned rows
is stored in $count variable
```php
$users = $db->get('users'); //contains an array of all users
$users = $db->get('users', 10); //contains an array 10 users
$users = $db->get('users'); //contains an Array of all users
$users = $db->get('users', 10); //contains an Array 10 users
```
or select with custom columns set. Functions also could be used
......@@ -41,9 +72,10 @@ echo "total ".$stats['cnt']. "users found";
$cols = Array ("id, name, email");
$users = $db->get ("users", null, $cols);
foreach ($users as $user) {
if ($db->count > 0)
foreach ($users as $user) {
print_r ($user);
}
}
```
or select just one row
......@@ -54,16 +86,6 @@ $user = $db->getOne ("users");
echo $user['id'];
```
### Update Query
```php
$data = array (
'firstName' => 'Bobby',
'lastName' => 'Tables'
);
$db->where('id', 1);
if($db->update('users', $data)) echo 'successfully updated';
```
### Delete Query
```php
$db->where('id', 1);
......@@ -80,14 +102,14 @@ foreach ($users as $user) {
### Raw Query Method
```php
$params = array(1, 'admin');
$params = Array(1, 'admin');
$users = $db->rawQuery("SELECT id, firstName, lastName FROM users WHERE id = ? AND login = ?", $params);
print_r($users); // contains array of returned rows
print_r($users); // contains Array of returned rows
// will handle any SQL query
$params = array(10, 1, 10, 11, 2, 10);
$params = Array(10, 1, 10, 11, 2, 10);
$resutls = $db->rawQuery("(SELECT a FROM t1 WHERE a = ? AND B = ? ORDER BY a LIMIT ?) UNION(SELECT a FROM t2 WHERE a = ? AND B = ? ORDER BY a LIMIT ?)", $params);
print_r($results); // contains array of returned rows
print_r($results); // contains Array of returned rows
```
......@@ -104,21 +126,21 @@ $results = $db->get('users');
Custom Operators:
```php
$db->where('id', array('>=' => 50));
$db->where('id', Array('>=' => 50));
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id >= 50;
```
BETWEEN:
```php
$db->where('id', array('between' => array(4, 20) ) );
$db->where('id', Array('between' => Array(4, 20) ) );
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id BETWEEN 4 AND 20
```
IN:
```php
$db->where('id', array( 'in' => array(1, 5, 27, -1, 'd') ) );
$db->where('id', Array( 'in' => Array(1, 5, 27, -1, 'd') ) );
$results = $db->get('users');
// Gives: SELECT * FROM users WHERE id IN (1, 5, 27, -1, 'd');
```
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment