1

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! This is exactly what I needed :)
You need to add additional parameters to ORDER BY if you want to control the ordering within the two groups. Otherwise the database orders them arbitrarily.
Nothing in my code forces the blank rows to the end.
OK, I've fixed it. Thanks Barmar!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.