Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Codeigniter Active Record - How do I do a where_in query and return the correct order of results?

I have a set of IDs passed in a particular order which needs to be retained. I am querying from several left joins the data related to each ID. The IDs are returned from a search so the order must be kept to make the results valid (otherwise it makes searching rather pointless).

My code looks something like;

$this->db->where_in('id', $array_of_ordered_ids);

For example -

$this->db->where_in('id', array(4,5,2,6));

Will return the results in order 2,4,5,6.

I'd like for it to retain the order and return the results 4,5,2,6.

Thank you,

like image 818
Anthony Avatar asked Sep 16 '11 10:09

Anthony


People also ask

How do you use order by in CI?

To sort query resultset in codeigniter you have to use order_by() method from 'Active Record Class' library. The method takes up two parameters, first one is the table column name and second one is optional and specifies if the column values should be sorted in ascending or decending order.

Which method returns an array of all the rows returned by the query?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

How check if query is successful in codeigniter?

// updates first of a user, return true if successful, false if not. public function updateFirstName($userId, $newFirstName) { $this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId"); return // whether request was successful? }


1 Answers

To order the result by the order in your array, you can do the following:

$array_of_ordered_ids = array(4,5,2,6);

As you already know the order of the numbers, you can use the Mysql FIELD()Docs function:

ORDER BY FIELD(id, 4, 5, 2, 6);

To create such a string, you can use implodeDocs:

$order = sprintf('FIELD(id, %s)', implode(', ', $array_of_ordered_ids));

Give it a try:

$array_of_ordered_ids = array(4,5,2,6);
$this->db->where_in('id', $array_of_ordered_ids);
$order = sprintf('FIELD(id, %s)', implode(', ', $array_of_ordered_ids));
$this->db->order_by($order); 
like image 90
hakre Avatar answered Sep 26 '22 00:09

hakre