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
44 changes: 40 additions & 4 deletions MysqliDb.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,23 @@ public function getOne($tableName, $columns = '*')
return null;
}

/**
* A convenient SELECT * function to get one value.
*
* @param string $tableName The name of the database table to work with.
*
* @return array Contains the returned column from the select query.
*/
public function getValue($tableName, $column)
{
$res = $this->get ($tableName, 1, "{$column} as retval");

if (isset($res[0]["retval"]))
return $res[0]["retval"];

return null;
}

/**
*
* @param <string $tableName The name of the table.
Expand All @@ -300,8 +317,15 @@ public function insert($tableName, $insertData)
$stmt->execute();
$this->_stmtError = $stmt->error;
$this->reset();
$this->count = $stmt->affected_rows;

if ($stmt->affected_rows < 1)
return false;

return ($stmt->affected_rows > 0 ? $stmt->insert_id : false);
if ($stmt->insert_id > 0)
return $stmt->insert_id;

return true;
}

/**
Expand Down Expand Up @@ -422,7 +446,7 @@ public function join($joinTable, $joinCondition, $joinType = '')
*
* @return MysqliDb
*/
public function orderBy($orderByField, $orderbyDirection = "DESC")
public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null)
{
$allowedDirection = Array ("ASC", "DESC");
$orderbyDirection = strtoupper (trim ($orderbyDirection));
Expand All @@ -431,6 +455,13 @@ public function orderBy($orderByField, $orderbyDirection = "DESC")
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);

$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")';
}

$this->_orderBy[$orderByField] = $orderbyDirection;
return $this;
}
Expand Down Expand Up @@ -627,6 +658,7 @@ protected function _dynamicBindResults(mysqli_stmt $stmt)

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

$this->count = 0;
while ($stmt->fetch()) {
$x = array();
foreach ($row as $key => $val) {
Expand Down Expand Up @@ -794,8 +826,12 @@ protected function _buildOrderBy () {
return;

$this->_query .= " ORDER BY ";
foreach ($this->_orderBy as $prop => $value)
$this->_query .= $prop . " " . $value . ", ";
foreach ($this->_orderBy as $prop => $value) {
if (strtolower (str_replace (" ", "", $prop)) == 'rand()')
$this->_query .= "rand(), ";
else
$this->_query .= $prop . " " . $value . ", ";
}

$this->_query = rtrim ($this->_query, ', ') . " ";
}
Expand Down
17 changes: 16 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,13 @@ $stats = $db->getOne ("users", "sum(id), count(*) as cnt");
echo "total ".$stats['cnt']. "users found";
```

or select one column or function result

```php
$count = getValue ("users", "count(*)");
echo "{$count} users found";
```

### Delete Query
```php
$db->where('id', 1);
Expand Down Expand Up @@ -254,8 +261,16 @@ $results = $db
```php
$db->orderBy("id","asc");
$db->orderBy("login","Desc");
$db->orderBy("RAND ()");
$results = $db->get('users');
// Gives: SELECT * FROM users ORDER BY id ASC,login DESC;
// Gives: SELECT * FROM users ORDER BY id ASC,login DESC, RAND ();
```

order by values example:
```php
$db->orderBy('userGroup', 'ASC', array('superuser', 'admin', 'users'));
$db->get('users');
// Gives: SELECT * FROM users ORDER BY FIELD (userGroup, 'superuser', 'admin', 'users') ASC;
```

### Grouping method
Expand Down
51 changes: 48 additions & 3 deletions tests.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,29 +93,70 @@ function createTable ($name, $data) {
$db->rawQuery($q);
}

// rawQuery test
foreach ($tables as $name => $fields) {
$db->rawQuery("DROP TABLE ".$prefix.$name);
createTable ($prefix.$name, $fields);
}


// insert test with autoincrement
foreach ($data as $name => $datas) {
foreach ($datas as $d) {
$id = $db->insert($name, $d);
if ($id)
$d['id'] = $id;
else {
echo "failed to insert: ".$db->getLastQuery() ."\n". $db->getLastError();
exit;
}
}
}

// bad insert test
$badUser = Array ('login' => null,
'customerId' => 10,
'firstName' => 'John',
'lastName' => 'Doe',
'password' => 'test',
'createdAt' => $db->now(),
'expires' => $db->now('+1Y'),
'loginCount' => $db->inc()
);
$id = $db->insert ("users", $badUser);
if ($id) {
echo "bad insert test failed";
exit;
}

// insert without autoincrement
$q = "create table {$prefix}test (id int(10), name varchar(10));";
$db->rawQuery($q);
$id = $db->insert ("test", Array ("id" => 1, "name" => "testname"));
if (!$id) {
echo "insert without autoincrement failed";
exit;
}
$db->get("test");
if ($db->count != 1) {
echo "insert without autoincrement failed -- wrong insert count";
exit;
}

$db->orderBy("id","asc");
$users = $db->get("users");
if ($db->count != 3) {
echo "Invalid total insert count";
exit;
}

// order by field
$db->orderBy("login","asc", Array ("user3","user2","user1"));
$login = $db->getValue ("users", "login");
if ($login != "user3") {
echo "order by field test failed";
exit;
}

$db->where ("active", true);
$users = $db->get("users");
if ($db->count != 1) {
Expand Down Expand Up @@ -246,8 +287,8 @@ function createTable ($name, $data) {

$db2 = $db->copy();
$db2->where ("userId", $usersQ);
$res = $db2->getOne ("products", "count(id) as cnt");
if ($res['cnt'] != 2) {
$cnt = $db2->getValue ("products", "count(id)");
if ($cnt != 2) {
echo "Invalid select result with subquery";
exit;
}
Expand All @@ -259,6 +300,10 @@ function createTable ($name, $data) {
exit;
}
$db->delete("products");

$q = "drop table {$prefix}test;";
$db->rawQuery($q);

echo "All done";

//print_r($db->rawQuery("CALL simpleproc(?)",Array("test")));
Expand Down