Commit 433ba3bd authored by Josh Campbell's avatar Josh Campbell

Merge pull request #194 from avbdr/master

Fixes an features
parents b4bd4cdc e5937d76
...@@ -283,6 +283,23 @@ class MysqliDb ...@@ -283,6 +283,23 @@ class MysqliDb
return null; 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. * @param <string $tableName The name of the table.
...@@ -300,8 +317,15 @@ class MysqliDb ...@@ -300,8 +317,15 @@ class MysqliDb
$stmt->execute(); $stmt->execute();
$this->_stmtError = $stmt->error; $this->_stmtError = $stmt->error;
$this->reset(); $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;
} }
/** /**
...@@ -422,7 +446,7 @@ class MysqliDb ...@@ -422,7 +446,7 @@ class MysqliDb
* *
* @return MysqliDb * @return MysqliDb
*/ */
public function orderBy($orderByField, $orderbyDirection = "DESC") public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null)
{ {
$allowedDirection = Array ("ASC", "DESC"); $allowedDirection = Array ("ASC", "DESC");
$orderbyDirection = strtoupper (trim ($orderbyDirection)); $orderbyDirection = strtoupper (trim ($orderbyDirection));
...@@ -431,6 +455,13 @@ class MysqliDb ...@@ -431,6 +455,13 @@ class MysqliDb
if (empty($orderbyDirection) || !in_array ($orderbyDirection, $allowedDirection)) if (empty($orderbyDirection) || !in_array ($orderbyDirection, $allowedDirection))
die ('Wrong order direction: '.$orderbyDirection); 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; $this->_orderBy[$orderByField] = $orderbyDirection;
return $this; return $this;
} }
...@@ -627,6 +658,7 @@ class MysqliDb ...@@ -627,6 +658,7 @@ class MysqliDb
call_user_func_array(array($stmt, 'bind_result'), $parameters); call_user_func_array(array($stmt, 'bind_result'), $parameters);
$this->count = 0;
while ($stmt->fetch()) { while ($stmt->fetch()) {
$x = array(); $x = array();
foreach ($row as $key => $val) { foreach ($row as $key => $val) {
...@@ -794,8 +826,12 @@ class MysqliDb ...@@ -794,8 +826,12 @@ class MysqliDb
return; return;
$this->_query .= " ORDER BY "; $this->_query .= " ORDER BY ";
foreach ($this->_orderBy as $prop => $value) foreach ($this->_orderBy as $prop => $value) {
if (strtolower (str_replace (" ", "", $prop)) == 'rand()')
$this->_query .= "rand(), ";
else
$this->_query .= $prop . " " . $value . ", "; $this->_query .= $prop . " " . $value . ", ";
}
$this->_query = rtrim ($this->_query, ', ') . " "; $this->_query = rtrim ($this->_query, ', ') . " ";
} }
......
...@@ -121,6 +121,13 @@ $stats = $db->getOne ("users", "sum(id), count(*) as cnt"); ...@@ -121,6 +121,13 @@ $stats = $db->getOne ("users", "sum(id), count(*) as cnt");
echo "total ".$stats['cnt']. "users found"; echo "total ".$stats['cnt']. "users found";
``` ```
or select one column or function result
```php
$count = getValue ("users", "count(*)");
echo "{$count} users found";
```
### Delete Query ### Delete Query
```php ```php
$db->where('id', 1); $db->where('id', 1);
...@@ -254,8 +261,16 @@ $results = $db ...@@ -254,8 +261,16 @@ $results = $db
```php ```php
$db->orderBy("id","asc"); $db->orderBy("id","asc");
$db->orderBy("login","Desc"); $db->orderBy("login","Desc");
$db->orderBy("RAND ()");
$results = $db->get('users'); $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 ### Grouping method
......
...@@ -93,12 +93,13 @@ function createTable ($name, $data) { ...@@ -93,12 +93,13 @@ function createTable ($name, $data) {
$db->rawQuery($q); $db->rawQuery($q);
} }
// rawQuery test
foreach ($tables as $name => $fields) { foreach ($tables as $name => $fields) {
$db->rawQuery("DROP TABLE ".$prefix.$name); $db->rawQuery("DROP TABLE ".$prefix.$name);
createTable ($prefix.$name, $fields); createTable ($prefix.$name, $fields);
} }
// insert test with autoincrement
foreach ($data as $name => $datas) { foreach ($data as $name => $datas) {
foreach ($datas as $d) { foreach ($datas as $d) {
$id = $db->insert($name, $d); $id = $db->insert($name, $d);
...@@ -106,16 +107,56 @@ foreach ($data as $name => $datas) { ...@@ -106,16 +107,56 @@ foreach ($data as $name => $datas) {
$d['id'] = $id; $d['id'] = $id;
else { else {
echo "failed to insert: ".$db->getLastQuery() ."\n". $db->getLastError(); 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"); $db->orderBy("id","asc");
$users = $db->get("users"); $users = $db->get("users");
if ($db->count != 3) { if ($db->count != 3) {
echo "Invalid total insert count"; echo "Invalid total insert count";
exit; 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); $db->where ("active", true);
$users = $db->get("users"); $users = $db->get("users");
if ($db->count != 1) { if ($db->count != 1) {
...@@ -246,8 +287,8 @@ $usersQ->getOne ("users", "id"); ...@@ -246,8 +287,8 @@ $usersQ->getOne ("users", "id");
$db2 = $db->copy(); $db2 = $db->copy();
$db2->where ("userId", $usersQ); $db2->where ("userId", $usersQ);
$res = $db2->getOne ("products", "count(id) as cnt"); $cnt = $db2->getValue ("products", "count(id)");
if ($res['cnt'] != 2) { if ($cnt != 2) {
echo "Invalid select result with subquery"; echo "Invalid select result with subquery";
exit; exit;
} }
...@@ -259,6 +300,10 @@ if ($db->count != 0) { ...@@ -259,6 +300,10 @@ if ($db->count != 0) {
exit; exit;
} }
$db->delete("products"); $db->delete("products");
$q = "drop table {$prefix}test;";
$db->rawQuery($q);
echo "All done"; echo "All done";
//print_r($db->rawQuery("CALL simpleproc(?)",Array("test"))); //print_r($db->rawQuery("CALL simpleproc(?)",Array("test")));
......
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