MySQL PHP - SELECT WHERE id = array()? [duplicate]

Possible Duplicate:
MySQL query using an array
Passing an array to mysql

I have an array in PHP:

$array = array(1, 4, 5, 7);

As you can see, I have an array of different values, but I want to write a MYSQL statement that will check if the id is equal to any of the values in the array. For example, if a row has an id of 1, it will return that row, the same for 4, 5, and 7. The length of the array can vary due to the nature of the program, so that's where the problem is. Could I just do:

SELECT ...
  FROM ...
 WHERE id = '$array'

Or is there a better way?
If I was unclear, please ask me for more info.


Use IN.

$sql = 'SELECT * 
          FROM `table` 
         WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';

What you are looking for is the IN() statement. This will test if a given field contains any of 1 or more values.

SELECT * FROM `Table` WHERE `id` IN (1, 2, 3)

You can use a simple loop to convert your $array variable into the proper format. Be sure to be mindful of SQL injection if your array values are coming from the front end.


Simply use the ID IN () syntax:

$sql = "SELECT FROM `table` WHERE `ID` IN (".implode(',',$array).")";

You can write your query like this:

select * from table where id in (1, 4, 6, 7)

You can add as many values as you need.