Reputation: 131
I have a list of id's in PHP. For example:
$id = (4,6,3,2,5,1)
When I perform a query like this:
$query = mysql_query("SELECT * FROM table WHERE ID IN ($id)");
it retrieves the results I want but the items are returned in the insertion order.
Instead, I want to retrieve the results in the order given in my array:
information 4, information 6, information 3, information 2, information 5, information 1
How can I do that?
Thanks guys! solution is ORDER BY FIELD (ID, $id);
Upvotes: 0
Views: 54
Reputation: 46910
$query="SELECT * FROM table WHERE ID IN ($id) ORDER BY FIND_IN_SET(ID,$id) DESC";
Also check this
Select query using IN() and without any sorting
Upvotes: 1
Reputation: 6950
Try this
$query = "SELECT * FROM table WHERE ID IN ($id) ORDER BY FIELD(ID,$id) ";
you can see this http://marco-pivetta.com/mysql-custom-sorting-rule-mysql/
Upvotes: 3
Reputation: 263733
You can use FIELD
on this,
SELECT *
FROM table
WHERE ID IN (4,6,3,2,5,1)
ORDER BY FIELD(ID, 4,6,3,2,5,1)
Upvotes: 1
Reputation: 191749
$query = "SELECT * FROM table WHERE ID IN ($id) ORDER BY ";
foreach ($id as $i) {
$query .= "ID = $i,";
}
$query = mysql_query(rtrim($query, ','));
Your code is vulnerable to injection. You should use properly parameterized queries with PDO or mysqli.
Upvotes: 1