Skip to content

Commit 387dc9d

Browse files
committed
Merge pull request #217 from avbdr/master
Bugfixes an features
2 parents ef942d6 + 76f43dd commit 387dc9d

File tree

3 files changed

+57
-15
lines changed

3 files changed

+57
-15
lines changed

MysqliDb.php

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class MysqliDb
6464
*/
6565
protected $_groupBy = array();
6666
/**
67-
* Dynamic array that holds a combination of where condition/table data value types and parameter referances
67+
* Dynamic array that holds a combination of where condition/table data value types and parameter references
6868
*
6969
* @var array
7070
*/
@@ -75,6 +75,13 @@ class MysqliDb
7575
* @var string
7676
*/
7777
public $count = 0;
78+
/**
79+
* Variable which holds an amount of returned rows during get/getOne/select queries with withTotalCount()
80+
*
81+
* @var string
82+
*/
83+
public $totalCount = 0;
84+
protected $fetchTotalCount = false;
7885
/**
7986
* Variable which holds last statement error
8087
*
@@ -253,6 +260,16 @@ public function query($query, $numRows = null)
253260
return $this->_dynamicBindResults($stmt);
254261
}
255262

263+
/**
264+
* Function to enable SQL_CALC_FOUND_ROWS in the get queries
265+
*
266+
* @return MysqliDb
267+
*/
268+
public function withTotalCount () {
269+
$this->fetchTotalCount = true;
270+
return $this;
271+
}
272+
256273
/**
257274
* A convenient SELECT * function.
258275
*
@@ -266,8 +283,9 @@ public function get($tableName, $numRows = null, $columns = '*')
266283
if (empty ($columns))
267284
$columns = '*';
268285

286+
$this->_query = $this->fetchTotalCount == true ? 'SELECT SQL_CALC_FOUND_ROWS ' : 'SELECT ';
269287
$column = is_array($columns) ? implode(', ', $columns) : $columns;
270-
$this->_query = "SELECT $column FROM " . self::$_prefix . $tableName;
288+
$this->_query .= "$column FROM " .self::$_prefix . $tableName;
271289
$stmt = $this->_buildQuery($numRows);
272290

273291
if ($this->isSubQuery)
@@ -329,7 +347,7 @@ public function insert($tableName, $insertData)
329347
if ($this->isSubQuery)
330348
return;
331349

332-
$this->_query = "INSERT into " .self::$_prefix . $tableName;
350+
$this->_query = "INSERT INTO " .self::$_prefix . $tableName;
333351
$stmt = $this->_buildQuery(null, $insertData);
334352
$stmt->execute();
335353
$this->_stmtError = $stmt->error;
@@ -372,7 +390,7 @@ public function update($tableName, $tableData)
372390
if ($this->isSubQuery)
373391
return;
374392

375-
$this->_query = "UPDATE " . self::$_prefix . $tableName ." SET ";
393+
$this->_query = "UPDATE " . self::$_prefix . $tableName;
376394

377395
$stmt = $this->_buildQuery (null, $tableData);
378396
$status = $stmt->execute();
@@ -483,14 +501,14 @@ public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields
483501
{
484502
$allowedDirection = Array ("ASC", "DESC");
485503
$orderbyDirection = strtoupper (trim ($orderbyDirection));
486-
$orderByField = preg_replace ("/[^-a-z0-9\.\(\),_]+/i",'', $orderByField);
504+
$orderByField = preg_replace ("/[^-a-z0-9\.\(\),_`]+/i",'', $orderByField);
487505

488506
if (empty($orderbyDirection) || !in_array ($orderbyDirection, $allowedDirection))
489507
die ('Wrong order direction: '.$orderbyDirection);
490508

491509
if (is_array ($customFields)) {
492510
foreach ($customFields as $key => $value)
493-
$customFields[$key] = preg_replace ("/[^-a-z0-9\.\(\),_]+/i",'', $value);
511+
$customFields[$key] = preg_replace ("/[^-a-z0-9\.\(\),_`]+/i",'', $value);
494512

495513
$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")';
496514
}
@@ -691,6 +709,7 @@ protected function _dynamicBindResults(mysqli_stmt $stmt)
691709

692710
call_user_func_array(array($stmt, 'bind_result'), $parameters);
693711

712+
$this->totalCount = 0;
694713
$this->count = 0;
695714
while ($stmt->fetch()) {
696715
$x = array();
@@ -701,6 +720,13 @@ protected function _dynamicBindResults(mysqli_stmt $stmt)
701720
array_push($results, $x);
702721
}
703722

723+
if ($this->fetchTotalCount === true) {
724+
$this->fetchTotalCount = false;
725+
$stmt = $this->_mysqli->query ('SELECT FOUND_ROWS();');
726+
$totalCount = $stmt->fetch_row();
727+
$this->totalCount = $totalCount[0];
728+
}
729+
704730
return $results;
705731
}
706732

@@ -735,9 +761,10 @@ protected function _buildTableData ($tableData) {
735761
$isUpdate = strpos ($this->_query, 'UPDATE');
736762

737763
if ($isInsert !== false) {
738-
$this->_query .= '(`' . implode(array_keys($tableData), '`, `') . '`)';
739-
$this->_query .= ' VALUES(';
740-
}
764+
$this->_query .= ' (`' . implode(array_keys($tableData), '`, `') . '`)';
765+
$this->_query .= ' VALUES (';
766+
} else
767+
$this->_query .= " SET ";
741768

742769
foreach ($tableData as $column => $value) {
743770
if ($isUpdate !== false)
@@ -791,7 +818,7 @@ protected function _buildWhere () {
791818
return;
792819

793820
//Prepair the where portion of the query
794-
$this->_query .= ' WHERE ';
821+
$this->_query .= ' WHERE';
795822

796823
// Remove first AND/OR concatenator
797824
$this->_where[0][0] = '';
@@ -950,7 +977,9 @@ protected function replacePlaceHolders ($str, $vals) {
950977
$val = $vals[$i++];
951978
if (is_object ($val))
952979
$val = '[object]';
953-
$newStr .= substr ($str, 0, $pos) . $val;
980+
if ($val == NULL)
981+
$val = 'NULL';
982+
$newStr .= substr ($str, 0, $pos) . "'". $val . "'";
954983
$str = substr ($str, $pos + 1);
955984
}
956985
$newStr .= $str;
@@ -1138,4 +1167,4 @@ public function _transaction_status_check () {
11381167
$this->rollback ();
11391168
}
11401169
} // END class
1141-
?>
1170+
?>

readme.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ echo "total ".$stats['cnt']. "users found";
142142
or select one column or function result
143143

144144
```php
145-
$count = getValue ("users", "count(*)");
145+
$count = $db->getValue ("users", "count(*)");
146146
echo "{$count} users found";
147147
```
148148

@@ -266,6 +266,14 @@ $res = $db->get ("users");
266266
```
267267

268268

269+
Find the total number of rows matched. Simple pagination example:
270+
```php
271+
$offset = 10;
272+
$count = 15;
273+
$users = $db->withTotalCount()->get('users', Array ($offset, $count));
274+
echo "Showing {$count} from {$db->totalCount}";
275+
```
276+
269277
Optionally you can use method chaining to call where multiple times without referencing your object over an over:
270278

271279
```php
@@ -310,7 +318,6 @@ print_r ($products);
310318
### Properties sharing
311319
Its is also possible to copy properties
312320

313-
Simple pagination example:
314321
```php
315322
$db->where ("agentId", 10);
316323
$db->where ("active", true);

tests.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ function createTable ($name, $data) {
157157
$db->rawQuery($q);
158158

159159

160-
$db->orderBy("id","asc");
160+
$db->orderBy("`id`","asc");
161161
$users = $db->get("users");
162162
if ($db->count != 3) {
163163
echo "Invalid total insert count";
@@ -340,6 +340,12 @@ function createTable ($name, $data) {
340340
echo "invalid join with subquery count";
341341
exit;
342342
}
343+
344+
$db->withTotalCount()->get('users', 1);
345+
if ($db->totalCount != 3) {
346+
echo "error in totalCount";
347+
exit;
348+
}
343349
///
344350
//TODO: insert test
345351
$db->delete("users");

0 commit comments

Comments
 (0)