This question already has an answer here:

I have table like this:

ID | title       | category
-----------------------------
1  | product1    | 0
2  | product2    | 0
3  | product3    | 1
4  | product4    | 1
5  | product5    | 3

I have array with ID's, how do I select products with those ID?

I mean something like this but category can be any value from array not only one value like in example.

$result = mysql_query("SELECT * FROM product where category = '$var'");
share|improve this question
Not like that. Use PDO or mysqli_*, and escape your variables. – Petah Mar 1 at 8:59
There is an example of this using PDO here: stackoverflow.com/questions/2373562/pdo-with-where-in-queries – Ken Mar 1 at 9:33

marked as duplicate by Petah, Mihai Iorga, cryptic ツ, hakre, Mahmoud Gamal Mar 1 at 9:15

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

up vote 0 down vote accepted
$ids = implode(',', $ids); // array(1,2,3,4) =>  '1,2,3,4'
$result = mysql_query("SELECT * FROM product WHERE category IN ('$ids')");
share|improve this answer
mysql_query is deprecated. – Petah Mar 1 at 9:00
3  
he asked how to do it in his case I gave him the answer what the problem? – gries Mar 1 at 9:01
Your answer will only lead to more problems – Petah Mar 1 at 9:02

Try this way

$arr = array(1,2);
$str = implode(',',$arr);

$result = mysql_query("SELECT * FROM product where category IN (".$str.") ");

Note that: Try to avoid the MySQL extenstions, try to use PDO or prepared statements instead.

share|improve this answer
mysql_query is deprecated. – Petah Mar 1 at 9:01
@Petah thanks for reminding about deprecation – GBD Mar 1 at 9:03

aside from out of date mysql_* functions and sql injection...

$result = mysql_query("SELECT * FROM product where category in ('$list_of_ids')");

share|improve this answer
mysql_query is deprecated. – Petah Mar 1 at 9:00
2  
i'm well aware of that and did link the op some other questions to make them aware too. the sql itself is the answer. – Pedro del Sol Mar 1 at 9:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.