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.
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);
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.
ASC: to sort the data in ascending order. DESC: to sort the data in descending order.
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.
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()
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With