Take the 2-minute tour ×

I'm wondering how to query a database using an array, like so:

$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");

$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.

Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:

$query = "";
foreach($friends as $friend){
  $query .= 'OR member_id = '.$friend[id.' ';
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");

Any help would be greatly appreciated, thanks!

share|improve this question
Quick tip: If your member_id's are INT's in the table, don't quote them. –  webbiedave May 11 '11 at 23:50
@webbiedave Yes you do quote INTs. MySQL does not magically convert the type of a value to string upon seeing quotes. Quotes designate value start and end. Not having to quote INTs is a much abused feature for lazy typers. –  Mel May 12 '11 at 0:24
@Mel: You are definitely in the minority on that one. –  webbiedave May 12 '11 at 4:53

3 Answers 3

up vote 5 down vote accepted

You want IN.

SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');

So the code changes to:

$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");

Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.

share|improve this answer

Use the SQL IN operator like so:

// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
    $instr .= $friend['member_id'].',';
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
share|improve this answer
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
substr($query, -3);
$result = mysql_query($query);
share|improve this answer
implode would be more appropriate for this activity, which is suspect to begin with - an IN would be better. –  Henry May 11 '11 at 23:51

Your Answer


