Advertisement
Advertisement


How to add an ORDER BY clause using CodeIgniter's Active Record methods?


Question

I have a very small script to get all records from a database table, the code is below.

$query = $this->db->get($this->table_name);
return $query->result();

Using this syntax, how would I add a ORDER BY 'name' clause to my select query?

I get errors every time I stick the order by bit on the end.

2020/06/28
1
59
6/28/2020 3:44:55 AM

Accepted Answer

I believe the get() function immediately runs the select query and does not accept ORDER BY conditions as parameters. I think you'll need to separately declare the conditions, then run the query. Give this a try:

$this->db->from($this->table_name);
$this->db->order_by("name", "asc");
$query = $this->db->get(); 
return $query->result();

CodeIgniter Documentation order_by()

2020/06/28
138
6/28/2020 3:39:30 AM

Using this code to multiple order by in single query.

$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get(); 
return $query->result();
2016/06/20

Simple and easy:

$this->db->order_by("name", "asc");
$query = $this->db->get($this->table_name);
return $query->result();
2015/06/16

Just add the'order_by' clause to your code and modify it to look just like the one below.

$this->db->order_by('name', 'asc');
$result = $this->db->get($table);

There you go.

2019/08/23

Source: https://stackoverflow.com/questions/5320395
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]