tags:

views:

6712

answers:

4

given an array

$galleries = array
         (
           [0] => 1
           [1] => 2
           [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?

A: 

select id from galleries where id in (1, 2, 5);

Simple for each loop will work.

EDIT: Flavius/AvatarKava's way is better, but make sure that none of the array values contain commas.

Matthew Flaschen
+11  A: 
 $ids = join(',',$galleries);  
 $sql = "SELECT * FROM galleries WHERE id IN ($ids)";
Flavius Stef
I think this technically won't work, since the entire string is encapsulated in double quotes.
AvatarKava
Agreed. Fixed the code.
Flavius Stef
The identifiers are still a quoted list, so it comes out as "WHERE id IN ( '1,2,3,4' )", for example. You need to quote each identifier separately, or else ditch the quotes inside the parentheses.
Rob
Actually, you can do..$ids = join("','", $galleries);$sql = "SELECT * FROM galleries WHERE id IN ('$ids')";
MiffTheFox
+2  A: 

Assuming you properly sanitize your inputs beforehand...

$matches = implode(',', $galleries);

Then just adjust your query:

SELECT *
FROM galleries
WHERE id IN ( $matches )

Quote values appropriately depending on your dataset.

AvatarKava
Yea, yours is better than mine was :P
Aiden Bell
A: 

$matches = implode(',', $galleries);

Does this work ? Doesn't need to be in quotes? Like:

$matches = implode('','', $galleries);

So that $matches can correspond to IN ( 'something', 'something', 'etc' ) in SQL ?

Or the IN statement accepts just the strings separated by commas?

Thank you

Pedro Teixeira