Skip to content

Commit dd37055

Browse files
authored
Adding ORDER BY REGEXP possibilites
Example of use: $MySqliDb->orderBy('name', 'desc', '^[a-zA-Z0-9]')->orderBy('name', 'desc'); // Is going to order by name but placing those name starting with special charaters at the end
1 parent b654510 commit dd37055

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

MysqliDb.php

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1061,16 +1061,16 @@ public function loadXml($importTable, $importFile, $importSettings = null)
10611061
/**
10621062
* This method allows you to specify multiple (method chaining optional) ORDER BY statements for SQL queries.
10631063
*
1064-
* @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc');
1064+
* @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc', '^[a-z]')->orderBy('name', 'desc');
10651065
*
10661066
* @param string $orderByField The name of the database field.
10671067
* @param string $orderByDirection Order direction.
1068-
* @param array $customFields Fieldset for ORDER BY FIELD() ordering
1068+
* @param mixed $customFieldsOrRegExp Array with fieldset for ORDER BY FIELD() ordering or string with regular expresion for ORDER BY REGEXP ordering
10691069
*
10701070
* @throws Exception
10711071
* @return MysqliDb
10721072
*/
1073-
public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null)
1073+
public function orderBy($orderByField, $orderbyDirection = "DESC", $customFieldsOrRegExp = null)
10741074
{
10751075
$allowedDirection = Array("ASC", "DESC");
10761076
$orderbyDirection = strtoupper(trim($orderbyDirection));
@@ -1086,13 +1086,16 @@ public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields
10861086
throw new Exception('Wrong order direction: ' . $orderbyDirection);
10871087
}
10881088

1089-
if (is_array($customFields)) {
1090-
foreach ($customFields as $key => $value) {
1091-
$customFields[$key] = preg_replace("/[^-a-z0-9\.\(\),_` ]+/i", '', $value);
1089+
if (is_array($customFieldsOrRegExp)) {
1090+
foreach ($customFieldsOrRegExp as $key => $value) {
1091+
$customFieldsOrRegExp[$key] = preg_replace("/[^-a-z0-9\.\(\),_` ]+/i", '', $value);
10921092
}
1093-
1094-
$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")';
1095-
}
1093+
$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFieldsOrRegExp) . '")';
1094+
}elseif(is_string($customFieldsOrRegExp)){
1095+
$orderByField = $orderByField . " REGEXP '" . $customFieldsOrRegExp . "'";
1096+
}elseif($customFieldsOrRegExp !== null){
1097+
throw new Exception('Wrong custom field or Regular Expression: ' . $customFieldsOrRegExp);
1098+
}
10961099

10971100
$this->_orderBy[$orderByField] = $orderbyDirection;
10981101
return $this;

0 commit comments

Comments
 (0)