PHP MySQL Select IN() Order by List
👤 By webune | 📆
This post is to document how to perform a query in PHP using MySQL for specific known Ids.
For example, I know the ids to be query therefore, the query may look like this:
$sql = "SELECT * FROM table WHERE id IN(1,4,3,2) ";
If you performed the above query, you might get an array like this [1,2,3,4]
However, I need the order of the query to be exactly as all the ids inside the IN() statement. The answer is the following:
ORDER BY FIELD(id, 1,4,3,2)
Now we can change our query to look like this:
$sql = "SELECT * FROM table WHERE id IN(1,2,3,4) ORDER BY FIELD(id, 1,4,3,2)";
your array query will look like this: [1,4,3,2] which is exactly how I wante it.
Hope that helps.