diff --git a/MysqliDb.php b/MysqliDb.php index fd547df6..3a9dfcb9 100644 --- a/MysqliDb.php +++ b/MysqliDb.php @@ -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 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; } /** @@ -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)); @@ -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; } @@ -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) { @@ -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, ', ') . " "; } diff --git a/readme.md b/readme.md index f3d1ca97..25b3c353 100644 --- a/readme.md +++ b/readme.md @@ -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); @@ -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 diff --git a/tests.php b/tests.php index e57a561a..f12b891e 100644 --- a/tests.php +++ b/tests.php @@ -93,12 +93,13 @@ 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); @@ -106,16 +107,56 @@ function createTable ($name, $data) { $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) { @@ -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; } @@ -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")));