1

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'");
LaKaede
  • 195
  • 1
  • 1
  • 13
  • Not like that. Use PDO or `mysqli_*`, and escape your variables. – Petah Mar 01 '13 at 08:59
  • There is an example of this using PDO here: http://stackoverflow.com/questions/2373562/pdo-with-where-in-queries – Ken Mar 01 '13 at 09:33

3 Answers3

3

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.

GBD
  • 15,847
  • 2
  • 46
  • 50
1
$ids = implode(',', $ids); // array(1,2,3,4) =>  '1,2,3,4'
$result = mysql_query("SELECT * FROM product WHERE category IN ('$ids')");
gries
  • 1,135
  • 6
  • 29
1

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

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

Community
  • 1
  • 1
Pedro del Sol
  • 2,840
  • 9
  • 39
  • 52