How to add an ORDER BY clause using CodeIgniter's Active Record methods?
To add an ORDER BY
clause to a query using CodeIgniter's Active Record class, you can use the order_by()
method. This method allows you to specify the column(s) that you want to sort by and the sort order (ascending or descending).
Here's an example of how you can use the order_by()
method in a query:
<?php
$this->db->order_by('title', 'asc');
$this->db->order_by('name', 'desc');
$query = $this->db->get('mytable');
This would generate a query that looks like this:
SELECT * FROM mytable ORDER BY title asc, name desc;
Watch a video course
Learn object oriented PHP
You can also use the order_by()
method in a chained manner:
<?php
$query = $this->db
->order_by('title', 'asc')
->order_by('name', 'desc')
->get('mytable');
If you want to specify a custom sort order for a column, you can pass an array to the order_by()
method, where the key is the column name and the value is the sort order. For example:
<?php
$this->db->order_by(array('title' => 'asc', 'name' => 'desc'));
$query = $this->db->get('mytable');
This would generate a query that looks like this:
SELECT * FROM mytable ORDER BY title asc, name desc;
We hope this helps! Let us know if you have any questions.