Skip to content

Commit 433ba3b

Browse files
committed
Merge pull request #194 from avbdr/master
Fixes an features
2 parents b4bd4cd + e5937d7 commit 433ba3b

File tree

3 files changed

+104
-8
lines changed

3 files changed

+104
-8
lines changed

MysqliDb.php

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,23 @@ public function getOne($tableName, $columns = '*')
283283
return null;
284284
}
285285

286+
/**
287+
* A convenient SELECT * function to get one value.
288+
*
289+
* @param string $tableName The name of the database table to work with.
290+
*
291+
* @return array Contains the returned column from the select query.
292+
*/
293+
public function getValue($tableName, $column)
294+
{
295+
$res = $this->get ($tableName, 1, "{$column} as retval");
296+
297+
if (isset($res[0]["retval"]))
298+
return $res[0]["retval"];
299+
300+
return null;
301+
}
302+
286303
/**
287304
*
288305
* @param <string $tableName The name of the table.
@@ -300,8 +317,15 @@ public function insert($tableName, $insertData)
300317
$stmt->execute();
301318
$this->_stmtError = $stmt->error;
302319
$this->reset();
320+
$this->count = $stmt->affected_rows;
321+
322+
if ($stmt->affected_rows < 1)
323+
return false;
303324

304-
return ($stmt->affected_rows > 0 ? $stmt->insert_id : false);
325+
if ($stmt->insert_id > 0)
326+
return $stmt->insert_id;
327+
328+
return true;
305329
}
306330

307331
/**
@@ -422,7 +446,7 @@ public function join($joinTable, $joinCondition, $joinType = '')
422446
*
423447
* @return MysqliDb
424448
*/
425-
public function orderBy($orderByField, $orderbyDirection = "DESC")
449+
public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null)
426450
{
427451
$allowedDirection = Array ("ASC", "DESC");
428452
$orderbyDirection = strtoupper (trim ($orderbyDirection));
@@ -431,6 +455,13 @@ public function orderBy($orderByField, $orderbyDirection = "DESC")
431455
if (empty($orderbyDirection) || !in_array ($orderbyDirection, $allowedDirection))
432456
die ('Wrong order direction: '.$orderbyDirection);
433457

458+
if (is_array ($customFields)) {
459+
foreach ($customFields as $key => $value)
460+
$customFields[$key] = preg_replace ("/[^-a-z0-9\.\(\),_]+/i",'', $value);
461+
462+
$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")';
463+
}
464+
434465
$this->_orderBy[$orderByField] = $orderbyDirection;
435466
return $this;
436467
}
@@ -627,6 +658,7 @@ protected function _dynamicBindResults(mysqli_stmt $stmt)
627658

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

661+
$this->count = 0;
630662
while ($stmt->fetch()) {
631663
$x = array();
632664
foreach ($row as $key => $val) {
@@ -794,8 +826,12 @@ protected function _buildOrderBy () {
794826
return;
795827

796828
$this->_query .= " ORDER BY ";
797-
foreach ($this->_orderBy as $prop => $value)
798-
$this->_query .= $prop . " " . $value . ", ";
829+
foreach ($this->_orderBy as $prop => $value) {
830+
if (strtolower (str_replace (" ", "", $prop)) == 'rand()')
831+
$this->_query .= "rand(), ";
832+
else
833+
$this->_query .= $prop . " " . $value . ", ";
834+
}
799835

800836
$this->_query = rtrim ($this->_query, ', ') . " ";
801837
}

readme.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,13 @@ $stats = $db->getOne ("users", "sum(id), count(*) as cnt");
121121
echo "total ".$stats['cnt']. "users found";
122122
```
123123

124+
or select one column or function result
125+
126+
```php
127+
$count = getValue ("users", "count(*)");
128+
echo "{$count} users found";
129+
```
130+
124131
### Delete Query
125132
```php
126133
$db->where('id', 1);
@@ -254,8 +261,16 @@ $results = $db
254261
```php
255262
$db->orderBy("id","asc");
256263
$db->orderBy("login","Desc");
264+
$db->orderBy("RAND ()");
257265
$results = $db->get('users');
258-
// Gives: SELECT * FROM users ORDER BY id ASC,login DESC;
266+
// Gives: SELECT * FROM users ORDER BY id ASC,login DESC, RAND ();
267+
```
268+
269+
order by values example:
270+
```php
271+
$db->orderBy('userGroup', 'ASC', array('superuser', 'admin', 'users'));
272+
$db->get('users');
273+
// Gives: SELECT * FROM users ORDER BY FIELD (userGroup, 'superuser', 'admin', 'users') ASC;
259274
```
260275

261276
### Grouping method

tests.php

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,29 +93,70 @@ function createTable ($name, $data) {
9393
$db->rawQuery($q);
9494
}
9595

96+
// rawQuery test
9697
foreach ($tables as $name => $fields) {
9798
$db->rawQuery("DROP TABLE ".$prefix.$name);
9899
createTable ($prefix.$name, $fields);
99100
}
100101

101-
102+
// insert test with autoincrement
102103
foreach ($data as $name => $datas) {
103104
foreach ($datas as $d) {
104105
$id = $db->insert($name, $d);
105106
if ($id)
106107
$d['id'] = $id;
107108
else {
108109
echo "failed to insert: ".$db->getLastQuery() ."\n". $db->getLastError();
110+
exit;
109111
}
110112
}
111113
}
112114

115+
// bad insert test
116+
$badUser = Array ('login' => null,
117+
'customerId' => 10,
118+
'firstName' => 'John',
119+
'lastName' => 'Doe',
120+
'password' => 'test',
121+
'createdAt' => $db->now(),
122+
'expires' => $db->now('+1Y'),
123+
'loginCount' => $db->inc()
124+
);
125+
$id = $db->insert ("users", $badUser);
126+
if ($id) {
127+
echo "bad insert test failed";
128+
exit;
129+
}
130+
131+
// insert without autoincrement
132+
$q = "create table {$prefix}test (id int(10), name varchar(10));";
133+
$db->rawQuery($q);
134+
$id = $db->insert ("test", Array ("id" => 1, "name" => "testname"));
135+
if (!$id) {
136+
echo "insert without autoincrement failed";
137+
exit;
138+
}
139+
$db->get("test");
140+
if ($db->count != 1) {
141+
echo "insert without autoincrement failed -- wrong insert count";
142+
exit;
143+
}
144+
113145
$db->orderBy("id","asc");
114146
$users = $db->get("users");
115147
if ($db->count != 3) {
116148
echo "Invalid total insert count";
117149
exit;
118150
}
151+
152+
// order by field
153+
$db->orderBy("login","asc", Array ("user3","user2","user1"));
154+
$login = $db->getValue ("users", "login");
155+
if ($login != "user3") {
156+
echo "order by field test failed";
157+
exit;
158+
}
159+
119160
$db->where ("active", true);
120161
$users = $db->get("users");
121162
if ($db->count != 1) {
@@ -246,8 +287,8 @@ function createTable ($name, $data) {
246287

247288
$db2 = $db->copy();
248289
$db2->where ("userId", $usersQ);
249-
$res = $db2->getOne ("products", "count(id) as cnt");
250-
if ($res['cnt'] != 2) {
290+
$cnt = $db2->getValue ("products", "count(id)");
291+
if ($cnt != 2) {
251292
echo "Invalid select result with subquery";
252293
exit;
253294
}
@@ -259,6 +300,10 @@ function createTable ($name, $data) {
259300
exit;
260301
}
261302
$db->delete("products");
303+
304+
$q = "drop table {$prefix}test;";
305+
$db->rawQuery($q);
306+
262307
echo "All done";
263308

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

0 commit comments

Comments
 (0)