Commit 16d88ae2 authored by Alexander Butenko's avatar Alexander Butenko

Merge pull request #284 from avbdr/master

fixes
parents 20db85d5 bd30f30d
...@@ -21,7 +21,7 @@ class MysqliDb ...@@ -21,7 +21,7 @@ class MysqliDb
protected static $_instance; protected static $_instance;
/** /**
* Table prefix * Table prefix
* *
* @var string * @var string
*/ */
public static $prefix = ''; public static $prefix = '';
...@@ -54,7 +54,7 @@ class MysqliDb ...@@ -54,7 +54,7 @@ class MysqliDb
* *
* @var array * @var array
*/ */
protected $_join = array(); protected $_join = array();
/** /**
* An array that holds where conditions 'fieldname' => 'value' * An array that holds where conditions 'fieldname' => 'value'
* *
...@@ -64,11 +64,11 @@ class MysqliDb ...@@ -64,11 +64,11 @@ class MysqliDb
/** /**
* Dynamic type list for order by condition value * Dynamic type list for order by condition value
*/ */
protected $_orderBy = array(); protected $_orderBy = array();
/** /**
* Dynamic type list for group by condition value * Dynamic type list for group by condition value
*/ */
protected $_groupBy = array(); protected $_groupBy = array();
/** /**
* Dynamic array that holds a combination of where condition/table data value types and parameter references * Dynamic array that holds a combination of where condition/table data value types and parameter references
* *
...@@ -79,13 +79,13 @@ class MysqliDb ...@@ -79,13 +79,13 @@ class MysqliDb
* Variable which holds an amount of returned rows during get/getOne/select queries * Variable which holds an amount of returned rows during get/getOne/select queries
* *
* @var string * @var string
*/ */
public $count = 0; public $count = 0;
/** /**
* Variable which holds an amount of returned rows during get/getOne/select queries with withTotalCount() * Variable which holds an amount of returned rows during get/getOne/select queries with withTotalCount()
* *
* @var string * @var string
*/ */
public $totalCount = 0; public $totalCount = 0;
/** /**
* Variable which holds last statement error * Variable which holds last statement error
...@@ -113,7 +113,7 @@ class MysqliDb ...@@ -113,7 +113,7 @@ class MysqliDb
protected $isSubQuery = false; protected $isSubQuery = false;
/** /**
* Name of the auto increment column * Name of the auto increment column
* *
*/ */
protected $_lastInsertId = null; protected $_lastInsertId = null;
...@@ -240,7 +240,7 @@ class MysqliDb ...@@ -240,7 +240,7 @@ class MysqliDb
$this->_where = array(); $this->_where = array();
$this->_join = array(); $this->_join = array();
$this->_orderBy = array(); $this->_orderBy = array();
$this->_groupBy = array(); $this->_groupBy = array();
$this->_bindParams = array(''); // Create the empty 0 index $this->_bindParams = array(''); // Create the empty 0 index
$this->_query = null; $this->_query = null;
$this->_queryOptions = array(); $this->_queryOptions = array();
...@@ -281,10 +281,10 @@ class MysqliDb ...@@ -281,10 +281,10 @@ class MysqliDb
$this->returnType = 'Object'; $this->returnType = 'Object';
return $this; return $this;
} }
/** /**
* Method to set a prefix * Method to set a prefix
* *
* @param string $prefix Contains a tableprefix * @param string $prefix Contains a tableprefix
*/ */
public function setPrefix($prefix = '') public function setPrefix($prefix = '')
...@@ -399,7 +399,7 @@ class MysqliDb ...@@ -399,7 +399,7 @@ class MysqliDb
if (empty ($columns)) if (empty ($columns))
$columns = '*'; $columns = '*';
$column = is_array($columns) ? implode(', ', $columns) : $columns; $column = is_array($columns) ? implode(', ', $columns) : $columns;
$this->_tableName = self::$prefix . $tableName; $this->_tableName = self::$prefix . $tableName;
$this->_query = 'SELECT ' . implode(' ', $this->_queryOptions) . ' ' . $this->_query = 'SELECT ' . implode(' ', $this->_queryOptions) . ' ' .
$column . " FROM " . $this->_tableName; $column . " FROM " . $this->_tableName;
...@@ -423,7 +423,7 @@ class MysqliDb ...@@ -423,7 +423,7 @@ class MysqliDb
* *
* @return array Contains the returned rows from the select query. * @return array Contains the returned rows from the select query.
*/ */
public function getOne($tableName, $columns = '*') public function getOne($tableName, $columns = '*')
{ {
$res = $this->get ($tableName, 1, $columns); $res = $this->get ($tableName, 1, $columns);
...@@ -444,7 +444,7 @@ class MysqliDb ...@@ -444,7 +444,7 @@ class MysqliDb
* *
* @return string Contains the value of a returned column. * @return string Contains the value of a returned column.
*/ */
public function getValue($tableName, $column) public function getValue($tableName, $column)
{ {
$res = $this->ArrayBuilder()->get ($tableName, 1, "{$column} as retval"); $res = $this->ArrayBuilder()->get ($tableName, 1, "{$column} as retval");
...@@ -563,12 +563,12 @@ class MysqliDb ...@@ -563,12 +563,12 @@ class MysqliDb
return $this; return $this;
} }
/** /**
* This function store update column's name and column name of the * This function store update column's name and column name of the
* autoincrement column * autoincrement column
* *
* @param Array Variable with values * @param Array Variable with values
* @param String Variable value * @param String Variable value
*/ */
public function onDuplicate($_updateColumns, $_lastInsertId = null) public function onDuplicate($_updateColumns, $_lastInsertId = null)
{ {
...@@ -632,7 +632,7 @@ class MysqliDb ...@@ -632,7 +632,7 @@ class MysqliDb
$orderbyDirection = strtoupper (trim ($orderbyDirection)); $orderbyDirection = strtoupper (trim ($orderbyDirection));
$orderByField = preg_replace ("/[^-a-z0-9\.\(\),_`]+/i",'', $orderByField); $orderByField = preg_replace ("/[^-a-z0-9\.\(\),_`]+/i",'', $orderByField);
// Add table prefix to orderByField if needed. // Add table prefix to orderByField if needed.
//FIXME: We are adding prefix only if table is enclosed into `` to distinguish aliases //FIXME: We are adding prefix only if table is enclosed into `` to distinguish aliases
// from table names // from table names
$orderByField = preg_replace('/(\`)([`a-zA-Z0-9_]*\.)/', '\1' . self::$prefix. '\2', $orderByField); $orderByField = preg_replace('/(\`)([`a-zA-Z0-9_]*\.)/', '\1' . self::$prefix. '\2', $orderByField);
...@@ -650,7 +650,7 @@ class MysqliDb ...@@ -650,7 +650,7 @@ class MysqliDb
$this->_orderBy[$orderByField] = $orderbyDirection; $this->_orderBy[$orderByField] = $orderbyDirection;
return $this; return $this;
} }
/** /**
* This method allows you to specify multiple (method chaining optional) GROUP BY statements for SQL queries. * This method allows you to specify multiple (method chaining optional) GROUP BY statements for SQL queries.
...@@ -667,7 +667,7 @@ class MysqliDb ...@@ -667,7 +667,7 @@ class MysqliDb
$this->_groupBy[] = $groupByField; $this->_groupBy[] = $groupByField;
return $this; return $this;
} }
/** /**
* This methods returns the ID of the last inserted item * This methods returns the ID of the last inserted item
...@@ -805,57 +805,6 @@ class MysqliDb ...@@ -805,57 +805,6 @@ class MysqliDb
return true; return true;
} }
/**
* Helper function to add variables into the query statement
*
* @param Array Variable with values
*/
protected function _buildDuplicate($tableData)
{
if (is_array($this->_updateColumns) && !empty($this->_updateColumns)) {
$this->_query .= " on duplicate key update ";
if ($this->_lastInsertId) {
$this->_lastQuery .= $this->_lastInsertId."=LAST_INSERT_ID(".$this->_lastInsertId."),";
$this->_lastInsertId = null;
}
foreach ($this->_updateColumns as $column) {
$this->_query .= "`" . $column . "` = ";
// Simple value
if (!is_array ($tableData[$column])) {
$this->_bindParam($tableData[$column]);
$this->_query .= '?, ';
continue;
}
// Function value
$arr = $tableData[$column];
$key = key($arr);
$val = $arr[$key];
switch ($key) {
case '[I]':
$this->_query .= $column . $val . ", ";
break;
case '[F]':
$this->_query .= $val[0] . ", ";
if (!empty ($val[1]))
$this->_bindParams ($val[1]);
break;
case '[N]':
if ($val == null)
$this->_query .= "!" . $column . ", ";
else
$this->_query .= "!" . $val . ", ";
break;
default:
die ("Wrong operation");
}
}
$this->_query = rtrim($this->_query, ', ');
}
}
/** /**
* Abstraction method that will compile the WHERE statement, * Abstraction method that will compile the WHERE statement,
* any passed update data, and the desired rows. * any passed update data, and the desired rows.
...@@ -870,12 +819,12 @@ class MysqliDb ...@@ -870,12 +819,12 @@ class MysqliDb
protected function _buildQuery($numRows = null, $tableData = null) protected function _buildQuery($numRows = null, $tableData = null)
{ {
$this->_buildJoin(); $this->_buildJoin();
$this->_buildTableData ($tableData); $this->_buildInsertQuery ($tableData);
$this->_buildWhere(); $this->_buildWhere();
$this->_buildGroupBy(); $this->_buildGroupBy();
$this->_buildOrderBy(); $this->_buildOrderBy();
$this->_buildLimit ($numRows); $this->_buildLimit ($numRows);
$this->_buildDuplicate($tableData); $this->_buildOnDuplicate($tableData);
$this->_lastQuery = $this->replacePlaceHolders ($this->_query, $this->_bindParams); $this->_lastQuery = $this->replacePlaceHolders ($this->_query, $this->_bindParams);
...@@ -912,7 +861,7 @@ class MysqliDb ...@@ -912,7 +861,7 @@ class MysqliDb
// if $meta is false yet sqlstate is true, there's no sql error but the query is // if $meta is false yet sqlstate is true, there's no sql error but the query is
// most likely an update/insert/delete which doesn't produce any results // most likely an update/insert/delete which doesn't produce any results
if(!$meta && $stmt->sqlstate) { if(!$meta && $stmt->sqlstate) {
return array(); return array();
} }
...@@ -996,20 +945,9 @@ class MysqliDb ...@@ -996,20 +945,9 @@ class MysqliDb
} }
} }
/** public function _buildDataPairs ($tableData, $tableColumns, $isInsert) {
* Abstraction method that will build an INSERT or UPDATE part of the query foreach ($tableColumns as $column) {
*/ $value = $tableData[$column];
protected function _buildTableData ($tableData) {
if (!is_array ($tableData))
return;
$isInsert = preg_match ('/^[INSERT|REPLACE]/', $this->_query);
if ($isInsert)
$this->_query .= ' (`' . implode(array_keys($tableData), '`, `') . '`) VALUES (';
else
$this->_query .= " SET ";
foreach ($tableData as $column => $value) {
if (!$isInsert) if (!$isInsert)
$this->_query .= "`" . $column . "` = "; $this->_query .= "`" . $column . "` = ";
...@@ -1021,7 +959,7 @@ class MysqliDb ...@@ -1021,7 +959,7 @@ class MysqliDb
// Simple value // Simple value
if (!is_array ($value)) { if (!is_array ($value)) {
$this->_bindParam ($value); $this->_bindParam($value);
$this->_query .= '?, '; $this->_query .= '?, ';
continue; continue;
} }
...@@ -1030,25 +968,59 @@ class MysqliDb ...@@ -1030,25 +968,59 @@ class MysqliDb
$key = key ($value); $key = key ($value);
$val = $value[$key]; $val = $value[$key];
switch ($key) { switch ($key) {
case '[I]': case '[I]':
$this->_query .= $column . $val . ", "; $this->_query .= $column . $val . ", ";
break; break;
case '[F]': case '[F]':
$this->_query .= $val[0] . ", "; $this->_query .= $val[0] . ", ";
if (!empty ($val[1])) if (!empty ($val[1]))
$this->_bindParams ($val[1]); $this->_bindParams ($val[1]);
break; break;
case '[N]': case '[N]':
if ($val == null) if ($val == null)
$this->_query .= "!" . $column . ", "; $this->_query .= "!" . $column . ", ";
else else
$this->_query .= "!" . $val . ", "; $this->_query .= "!" . $val . ", ";
break; break;
default: default:
die ("Wrong operation"); die ("Wrong operation");
} }
} }
$this->_query = rtrim ($this->_query, ', '); $this->_query = rtrim($this->_query, ', ');
}
/**
* Helper function to add variables into the query statement
*
* @param Array Variable with values
*/
protected function _buildOnDuplicate($tableData)
{
if (is_array($this->_updateColumns) && !empty($this->_updateColumns)) {
$this->_query .= " on duplicate key update ";
if ($this->_lastInsertId)
$this->_query .= $this->_lastInsertId . "=LAST_INSERT_ID (".$this->_lastInsertId."), ";
$this->_buildDataPairs ($tableData, $this->_updateColumns, false);
}
}
/**
* Abstraction method that will build an INSERT or UPDATE part of the query
*/
protected function _buildInsertQuery ($tableData) {
if (!is_array ($tableData))
return;
$isInsert = preg_match ('/^[INSERT|REPLACE]/', $this->_query);
$dataColumns = array_keys ($tableData);
if ($isInsert)
$this->_query .= ' (`' . implode ($dataColumns, '`, `') . '`) VALUES (';
else
$this->_query .= " SET ";
$this->_buildDataPairs ($tableData, $dataColumns, $isInsert);
if ($isInsert) if ($isInsert)
$this->_query .= ')'; $this->_query .= ')';
} }
...@@ -1234,7 +1206,7 @@ class MysqliDb ...@@ -1234,7 +1206,7 @@ class MysqliDb
/** /**
* Method returns mysql error * Method returns mysql error
* *
* @return string * @return string
*/ */
public function getLastError () { public function getLastError () {
...@@ -1246,7 +1218,7 @@ class MysqliDb ...@@ -1246,7 +1218,7 @@ class MysqliDb
/** /**
* Mostly internal method to get query and its params out of subquery object * Mostly internal method to get query and its params out of subquery object
* after get() and getAll() * after get() and getAll()
* *
* @return array * @return array
*/ */
public function getSubQuery () { public function getSubQuery () {
...@@ -1321,7 +1293,7 @@ class MysqliDb ...@@ -1321,7 +1293,7 @@ class MysqliDb
public function dec ($num = 1) { public function dec ($num = 1) {
return Array ("[I]" => "-" . (int)$num); return Array ("[I]" => "-" . (int)$num);
} }
/** /**
* Method generates change boolean function call * Method generates change boolean function call
* @param string column name. null by default * @param string column name. null by default
......
...@@ -11,7 +11,7 @@ $db = new Mysqlidb($mysqli); ...@@ -11,7 +11,7 @@ $db = new Mysqlidb($mysqli);
$db = new Mysqlidb(Array ( $db = new Mysqlidb(Array (
'host' => 'localhost', 'host' => 'localhost',
'username' => 'root', 'username' => 'root',
'password' => '', 'password' => '',
'db' => 'testdb', 'db' => 'testdb',
'prefix' => $prefix, 'prefix' => $prefix,
...@@ -102,6 +102,7 @@ $data = Array ( ...@@ -102,6 +102,7 @@ $data = Array (
function createTable ($name, $data) { function createTable ($name, $data) {
global $db; global $db;
//$q = "CREATE TABLE $name (id INT(9) UNSIGNED PRIMARY KEY NOT NULL"; //$q = "CREATE TABLE $name (id INT(9) UNSIGNED PRIMARY KEY NOT NULL";
$db->rawQuery("DROP TABLE IF EXISTS $name");
$q = "CREATE TABLE $name (id INT(9) UNSIGNED PRIMARY KEY AUTO_INCREMENT"; $q = "CREATE TABLE $name (id INT(9) UNSIGNED PRIMARY KEY AUTO_INCREMENT";
foreach ($data as $k => $v) { foreach ($data as $k => $v) {
$q .= ", $k $v"; $q .= ", $k $v";
...@@ -192,6 +193,15 @@ $updateColumns = Array ("updatedAt"); ...@@ -192,6 +193,15 @@ $updateColumns = Array ("updatedAt");
$insertLastId = "id"; $insertLastId = "id";
$db->onDuplicate($updateColumns, "id"); $db->onDuplicate($updateColumns, "id");
$db->insert("users", $user); $db->insert("users", $user);
$nUser = $db->where('login','user3')->get('users');
if ($db->count != 1) {
echo "onDuplicate update failed. ";
exit;
}
if ($nUser[0]['createdAt'] == $nUser[0]['updatedAt']) {
echo "onDuplicate2 update failed. ";
exit;
}
// order by field // order by field
$db->orderBy("login","asc", Array ("user3","user2","user1")); $db->orderBy("login","asc", Array ("user3","user2","user1"));
...@@ -380,7 +390,7 @@ if ($db->totalCount != 3) { ...@@ -380,7 +390,7 @@ if ($db->totalCount != 3) {
$db->delete("users"); $db->delete("users");
$db->get("users"); $db->get("users");
if ($db->count != 0) { if ($db->count != 0) {
echo "Invalid users count after delete"; echo "Invalid users count after delete";
exit; exit;
} }
$db->delete("products"); $db->delete("products");
......
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