Given an array of ids $galleries = array(1,2,5)
I want to have a SQL query that uses the values of the array in its WHERE clause like:
SELECT *
FROM galleries
WHERE id = /* values of array $galleries... eg. (1 || 2 || 5) */
How can I generate this query string to use with MySQL?
As Flavius Stef's answer, you can use
intval()
to make sure allid
are int values:Assuming you properly sanitize your inputs beforehand...
Then just adjust your query:
Quote values appropriately depending on your dataset.
We can use this "WHERE id IN" clause if we filter the input array properly. Something like this:
Like the example below:
I.e. now you should safely use
$query = "SELECT * FROM galleries WHERE id IN ({$galleryIds})";
Because the original question relates to an array of numbers and I am using an array of strings I couldn't make the given examples work.
I found that each string needed to be encapsulated in single quotes to work with the
IN()
function.Here is my solution
As you can see the first function wraps each array variable in
single quotes (\')
and then implodes the array.NOTE:
$status
does not have single quotes in the SQL statement.There is probably a nicer way to add the quotes but this works.
Besides using the IN query, you have two options to do so as in an IN query there is a risk of an SQL injection vulnerability. You can use looping to get the exact data you want or you can use the query with OR case
ints:
strings: