orderBy() and order()
The orderBy()
and order()
methods define the sort direction of query results. Both accept a column and an optional sort direction, but differ in their default behavior:
- orderBy() defaults to
DESC
– commonly used to show newest or latest entries first. - order() defaults to
ASC
– useful for alphabetical or oldest-first sorting.
Signature:
public function orderBy(string $field, string $direction = 'DESC'): self
public function order(string $field, string $direction = 'ASC'): self
Sort by Created Date (Newest First)
$db->orderBy('created_at');
Sort by Created Date (Oldest First)
$db->orderBy('created_at', 'ASC');
Alphabetical Order
$db->order('name');
Reverse Alphabetical Order
$db->order('name', 'DESC');
Multiple Sorts
Chaining both methods is allowed and builds a composite ORDER BY clause:
$db->order('type')->orderBy('created_at');
Validation Rules
- Only safe column names are accepted (alphanumeric with dots or underscores).
- Allowed directions:
ASC
,DESC
(case-insensitive). - Raw SQL functions like
RAND()
are rejected unless explicitly marked as safe with[F]
. - Invalid input such as
SLEEP(1)
or1=1
will throw an exception.
Note: The default behavior of
While descending sort by default (newest first) can be useful for logs or entries with timestamps, it's not always intuitive. The
This separation ensures full compatibility with legacy usage while offering clarity for modern implementations.
orderBy()
using DESC
is inherited from the original MysqliDB library by ThingEngineer.
While descending sort by default (newest first) can be useful for logs or entries with timestamps, it's not always intuitive. The
order()
method exists to provide a more logical default of ASC
.
This separation ensures full compatibility with legacy usage while offering clarity for modern implementations.