Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 41 additions & 12 deletions MysqliDb.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -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
*
Expand Down Expand Up @@ -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.
*
Expand All @@ -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)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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) . '")';
}
Expand Down Expand Up @@ -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();
Expand All @@ -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;
}

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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] = '';
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1138,4 +1167,4 @@ public function _transaction_status_check () {
$this->rollback ();
}
} // END class
?>
?>
11 changes: 9 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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";
```

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 7 additions & 1 deletion tests.php
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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");
Expand Down