Skip to content

Commit e5937d7

Browse files
committed
Order by field support
1 parent 06f6a37 commit e5937d7

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

MysqliDb.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ public function join($joinTable, $joinCondition, $joinType = '')
446446
*
447447
* @return MysqliDb
448448
*/
449-
public function orderBy($orderByField, $orderbyDirection = "DESC")
449+
public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null)
450450
{
451451
$allowedDirection = Array ("ASC", "DESC");
452452
$orderbyDirection = strtoupper (trim ($orderbyDirection));
@@ -455,6 +455,13 @@ public function orderBy($orderByField, $orderbyDirection = "DESC")
455455
if (empty($orderbyDirection) || !in_array ($orderbyDirection, $allowedDirection))
456456
die ('Wrong order direction: '.$orderbyDirection);
457457

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+
458465
$this->_orderBy[$orderByField] = $orderbyDirection;
459466
return $this;
460467
}

readme.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,13 @@ $results = $db->get('users');
266266
// Gives: SELECT * FROM users ORDER BY id ASC,login DESC, RAND ();
267267
```
268268

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;
274+
```
275+
269276
### Grouping method
270277
```php
271278
$db->groupBy ("name");

tests.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,14 @@ function createTable ($name, $data) {
149149
exit;
150150
}
151151

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+
152160
$db->where ("active", true);
153161
$users = $db->get("users");
154162
if ($db->count != 1) {

0 commit comments

Comments
 (0)