From dd37055babd42974a8f6dfa3e1ba6ac25d4dde1e Mon Sep 17 00:00:00 2001 From: thingNumber1 Date: Tue, 7 Mar 2017 05:26:58 -0400 Subject: [PATCH] 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 --- MysqliDb.php | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/MysqliDb.php b/MysqliDb.php index d4bedc12..60330bb1 100644 --- a/MysqliDb.php +++ b/MysqliDb.php @@ -1061,16 +1061,16 @@ public function loadXml($importTable, $importFile, $importSettings = null) /** * This method allows you to specify multiple (method chaining optional) ORDER BY statements for SQL queries. * - * @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc'); + * @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc', '^[a-z]')->orderBy('name', 'desc'); * * @param string $orderByField The name of the database field. * @param string $orderByDirection Order direction. - * @param array $customFields Fieldset for ORDER BY FIELD() ordering + * @param mixed $customFieldsOrRegExp Array with fieldset for ORDER BY FIELD() ordering or string with regular expresion for ORDER BY REGEXP ordering * * @throws Exception * @return MysqliDb */ - public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null) + public function orderBy($orderByField, $orderbyDirection = "DESC", $customFieldsOrRegExp = null) { $allowedDirection = Array("ASC", "DESC"); $orderbyDirection = strtoupper(trim($orderbyDirection)); @@ -1086,13 +1086,16 @@ public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields throw new Exception('Wrong order direction: ' . $orderbyDirection); } - if (is_array($customFields)) { - foreach ($customFields as $key => $value) { - $customFields[$key] = preg_replace("/[^-a-z0-9\.\(\),_` ]+/i", '', $value); + if (is_array($customFieldsOrRegExp)) { + foreach ($customFieldsOrRegExp as $key => $value) { + $customFieldsOrRegExp[$key] = preg_replace("/[^-a-z0-9\.\(\),_` ]+/i", '', $value); } - - $orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")'; - } + $orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFieldsOrRegExp) . '")'; + }elseif(is_string($customFieldsOrRegExp)){ + $orderByField = $orderByField . " REGEXP '" . $customFieldsOrRegExp . "'"; + }elseif($customFieldsOrRegExp !== null){ + throw new Exception('Wrong custom field or Regular Expression: ' . $customFieldsOrRegExp); + } $this->_orderBy[$orderByField] = $orderbyDirection; return $this;