0

I am wondering how i can find all rows that have the same ID as one of the values in an array.. so lets say:

Array(1,2,5,6,99,467);

Now i want to query all rows which have an id in that array, my initial idea was to loop the array and use a SELECT on each field, but i am wondering if i can skip that process with some kind of in_array method to make a bit more efficient?

1 Answer 1

4
SELECT * 
FROM table
WHERE id IN (' . implode(', ', $arr) . ')

PS: if the data comes from outside and can contain non-numbers - it could worth performing array_map('intval', $arr) before

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

7 Comments

If i am using PDO for my queries, like this: $stmt->execute(array($array_data)); Will that still escape the array data for safe input ?
@Dave: PDO doesn't have facilities for sanitizing the data presented as array. You need to do that yourself. PS: it doesn't accept arrays as a parameters as well
how would i sanitize the data inside the array before hand ?
@Dave: If there are only numbers in array - then just $arr = array_map('intval', $arr);
@zerkms I know I thought that as I wrote it - but it could potentially be useful if you have to insert multiple rows based on many arrays of a fixed length, or if you want to allow non-numeric types. It does cut out the array_map() call, but I suspect that what you gain there would be lost on the array_fill() plus the additional round trip to the DB.
|

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.