Reputation: 204
column_x of a mySQL database contains values that might exist in a php array.
I want to query the database and prioritise any rows where the value for column_x exists in the PHP array.
My initial idea was to select a column_y that is 1 if column_x exists in the php array and 0 otherwise and then ORDER BY column_y DESC. Is this possible? If so, how do I go about it? Or, is there a better way to go about this?
Thanks!
Upvotes: 1
Views: 44
Reputation: 781096
You can use ORDER BY column_x IN (list of values) DESC
. When the condition is true, the value is 1
, otherwise it's 0
.
$array = array(1, 3, 4, 6);
$str = implode(', ', $array);
$sql = "SELECT * FROM yourTable
ORDER BY column_x IN ($str) DESC";
If the values come from user input, make sure you sanitize them before inserting into the SQL.
Upvotes: 1