How to query a database with an array? WHERE = 'array()'

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!

Asked By: Dan
||

Answer #1:

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.

Answered By: Dan

Answer #2:

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)");
Answered By: Erik Nedwidek

Answer #3:

$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);
Answered By: Matthew Smith
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles