Tags
Asked 3 years ago
17 Jun 2021
Views 276
Teagan

Teagan posted

how to set custom order_by in query at Codeigniter

how to set custom order_by in query at Codeigniter
denyy

denyy
answered Apr 27 '23 00:00

To set a custom order_by clause in a CodeIgniter query, you can pass a string as the second argument to the $this->db->order_by() method.

Here's an example of how to set a custom order_by clause in a CodeIgniter query:



$this->db->select('*');
$this->db->from('my_table');
$this->db->where('my_column', $my_value);
$this->db->order_by('FIELD(my_column, "value1", "value2", "value3")');
$query = $this->db->get();

In this example, we are selecting all columns from a table named " my_table " where the value of " my_column " equals "$my_value". We are then using the $this->db->order_by() method to set a custom order_by clause using the FIELD function, which sorts the results based on the order of the values provided.

You can modify the example to suit your specific query needs, changing the table name, column names, and values as necessary.

Note that when using a custom order_by clause, you need to be careful to avoid SQL injection vulnerabilities by properly sanitizing the values used in the query. You can use CodeIgniter's query bindings to safely escape user input and avoid SQL injection.
Post Answer