diff --git a/MysqliDb.php b/MysqliDb.php index 6166a6f3..7d5be393 100644 --- a/MysqliDb.php +++ b/MysqliDb.php @@ -64,7 +64,7 @@ class MysqliDb */ protected $_groupBy = array(); /** - * Dynamic array that holds a combination of where condition/table data value types and parameter referances + * Dynamic array that holds a combination of where condition/table data value types and parameter references * * @var array */ @@ -75,6 +75,13 @@ class MysqliDb * @var string */ public $count = 0; + /** + * Variable which holds an amount of returned rows during get/getOne/select queries with withTotalCount() + * + * @var string + */ + public $totalCount = 0; + protected $fetchTotalCount = false; /** * Variable which holds last statement error * @@ -253,6 +260,16 @@ public function query($query, $numRows = null) return $this->_dynamicBindResults($stmt); } + /** + * Function to enable SQL_CALC_FOUND_ROWS in the get queries + * + * @return MysqliDb + */ + public function withTotalCount () { + $this->fetchTotalCount = true; + return $this; + } + /** * A convenient SELECT * function. * @@ -266,8 +283,9 @@ public function get($tableName, $numRows = null, $columns = '*') if (empty ($columns)) $columns = '*'; + $this->_query = $this->fetchTotalCount == true ? 'SELECT SQL_CALC_FOUND_ROWS ' : 'SELECT '; $column = is_array($columns) ? implode(', ', $columns) : $columns; - $this->_query = "SELECT $column FROM " . self::$_prefix . $tableName; + $this->_query .= "$column FROM " .self::$_prefix . $tableName; $stmt = $this->_buildQuery($numRows); if ($this->isSubQuery) @@ -329,7 +347,7 @@ public function insert($tableName, $insertData) if ($this->isSubQuery) return; - $this->_query = "INSERT into " .self::$_prefix . $tableName; + $this->_query = "INSERT INTO " .self::$_prefix . $tableName; $stmt = $this->_buildQuery(null, $insertData); $stmt->execute(); $this->_stmtError = $stmt->error; @@ -372,7 +390,7 @@ public function update($tableName, $tableData) if ($this->isSubQuery) return; - $this->_query = "UPDATE " . self::$_prefix . $tableName ." SET "; + $this->_query = "UPDATE " . self::$_prefix . $tableName; $stmt = $this->_buildQuery (null, $tableData); $status = $stmt->execute(); @@ -483,14 +501,14 @@ public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields { $allowedDirection = Array ("ASC", "DESC"); $orderbyDirection = strtoupper (trim ($orderbyDirection)); - $orderByField = preg_replace ("/[^-a-z0-9\.\(\),_]+/i",'', $orderByField); + $orderByField = preg_replace ("/[^-a-z0-9\.\(\),_`]+/i",'', $orderByField); if (empty($orderbyDirection) || !in_array ($orderbyDirection, $allowedDirection)) die ('Wrong order direction: '.$orderbyDirection); if (is_array ($customFields)) { foreach ($customFields as $key => $value) - $customFields[$key] = preg_replace ("/[^-a-z0-9\.\(\),_]+/i",'', $value); + $customFields[$key] = preg_replace ("/[^-a-z0-9\.\(\),_`]+/i",'', $value); $orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")'; } @@ -691,6 +709,7 @@ protected function _dynamicBindResults(mysqli_stmt $stmt) call_user_func_array(array($stmt, 'bind_result'), $parameters); + $this->totalCount = 0; $this->count = 0; while ($stmt->fetch()) { $x = array(); @@ -701,6 +720,13 @@ protected function _dynamicBindResults(mysqli_stmt $stmt) array_push($results, $x); } + if ($this->fetchTotalCount === true) { + $this->fetchTotalCount = false; + $stmt = $this->_mysqli->query ('SELECT FOUND_ROWS();'); + $totalCount = $stmt->fetch_row(); + $this->totalCount = $totalCount[0]; + } + return $results; } @@ -735,9 +761,10 @@ protected function _buildTableData ($tableData) { $isUpdate = strpos ($this->_query, 'UPDATE'); if ($isInsert !== false) { - $this->_query .= '(`' . implode(array_keys($tableData), '`, `') . '`)'; - $this->_query .= ' VALUES('; - } + $this->_query .= ' (`' . implode(array_keys($tableData), '`, `') . '`)'; + $this->_query .= ' VALUES ('; + } else + $this->_query .= " SET "; foreach ($tableData as $column => $value) { if ($isUpdate !== false) @@ -791,7 +818,7 @@ protected function _buildWhere () { return; //Prepair the where portion of the query - $this->_query .= ' WHERE '; + $this->_query .= ' WHERE'; // Remove first AND/OR concatenator $this->_where[0][0] = ''; @@ -950,7 +977,9 @@ protected function replacePlaceHolders ($str, $vals) { $val = $vals[$i++]; if (is_object ($val)) $val = '[object]'; - $newStr .= substr ($str, 0, $pos) . $val; + if ($val == NULL) + $val = 'NULL'; + $newStr .= substr ($str, 0, $pos) . "'". $val . "'"; $str = substr ($str, $pos + 1); } $newStr .= $str; @@ -1138,4 +1167,4 @@ public function _transaction_status_check () { $this->rollback (); } } // END class -?> \ No newline at end of file +?> diff --git a/readme.md b/readme.md index 06079962..21d0cd96 100644 --- a/readme.md +++ b/readme.md @@ -142,7 +142,7 @@ echo "total ".$stats['cnt']. "users found"; or select one column or function result ```php -$count = getValue ("users", "count(*)"); +$count = $db->getValue ("users", "count(*)"); echo "{$count} users found"; ``` @@ -266,6 +266,14 @@ $res = $db->get ("users"); ``` +Find the total number of rows matched. Simple pagination example: +```php +$offset = 10; +$count = 15; +$users = $db->withTotalCount()->get('users', Array ($offset, $count)); +echo "Showing {$count} from {$db->totalCount}"; +``` + Optionally you can use method chaining to call where multiple times without referencing your object over an over: ```php @@ -310,7 +318,6 @@ print_r ($products); ### Properties sharing Its is also possible to copy properties -Simple pagination example: ```php $db->where ("agentId", 10); $db->where ("active", true); diff --git a/tests.php b/tests.php index 0a708730..bff6360d 100644 --- a/tests.php +++ b/tests.php @@ -157,7 +157,7 @@ function createTable ($name, $data) { $db->rawQuery($q); -$db->orderBy("id","asc"); +$db->orderBy("`id`","asc"); $users = $db->get("users"); if ($db->count != 3) { echo "Invalid total insert count"; @@ -340,6 +340,12 @@ function createTable ($name, $data) { echo "invalid join with subquery count"; exit; } + +$db->withTotalCount()->get('users', 1); +if ($db->totalCount != 3) { + echo "error in totalCount"; + exit; +} /// //TODO: insert test $db->delete("users");