Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 227
Cecil Avatar asked Mar 16 '11 02:03

Cecil


People also ask

How to add order by in CodeIgniter?

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);

What is CI Active Record?

Active Record Class CodeIgniter uses a modified version of the Active Record Database Pattern. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action.

What is DESC and ASC in SQL?

ASC: to sort the data in ascending order. DESC: to sort the data in descending order.

How do I arrange in ascending order in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


2 Answers

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()

like image 82
Ted Avery Avatar answered Oct 09 '22 00:10

Ted Avery


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(); 
like image 43
Naresh Kumar Avatar answered Oct 09 '22 02:10

Naresh Kumar