📜  codeigniter order by - PHP (1)

📅  最后修改于: 2023-12-03 15:30:02.389000             🧑  作者: Mango

CodeIgniter Order by - PHP

When dealing with databases in web development, it is common to sort the results of queries in a specific order. This can be achieved using the ORDER BY clause in SQL. In CodeIgniter, we can use the order_by() method to sort query results.

Syntax
$this->db->order_by('column_name', 'ASC/DESC');
  • column_name: the name of the column to sort by
  • ASC/DESC: the order in which to sort the results (ASC for ascending and DESC for descending)
Example

Suppose we have a table called users with the following columns:

id  | name   | email             | age
--------------------------------------
1   | Alice  | alice@example.com | 25
2   | Bob    | bob@example.com   | 30
3   | Charlie| charlie@example.com| 20

To retrieve all users sorted by age in ascending order, we can use the following code:

$query = $this->db->order_by('age', 'ASC')->get('users');

To retrieve all users sorted by name in descending order, we can use the following code:

$query = $this->db->order_by('name', 'DESC')->get('users');
Final thoughts

The order_by() method is a quick and easy way to sort query results in CodeIgniter. It also allows for sorting by multiple columns and is flexible enough to handle most sorting needs.