0

I am trying to use a SELECT query to select 3 rows, but I want them in the same order I call for them. This is what I attempted to do:

$array = array("50", "23", "67");
$list = implode(",", $array);

foreach($db->query("SELECT * FROM champs WHERE id IN ($list) ORDER BY 
    DECODE(id, $array[0], 1, $array[1], 2, $array[2], 3)") as $row) {
    //Do stuff
}   

however, I get:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

is there a way to ensure it is always returned in the order I call it?

1 Answer 1

1

decode() is an Oracle function, not a MySQL function. You should use case, which works in both databases:

SELECT *
FROM champs
WHERE id IN ($list)
ORDER BY (CASE WHEN id = $array[0] THEN 1
               WHEN id = $array[1] THEN 2
               WHEN id = $array[2] THEN 3
          END);
Sign up to request clarification or add additional context in comments.

Comments

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.