0

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!

Dan
  • 41
  • 3
  • 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 00:24
  • 1
    @Mel: You are definitely in the minority on that one. – webbiedave May 12 '11 at 04:53

3 Answers3

5

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Erik Nedwidek
  • 6,134
  • 1
  • 25
  • 25
0

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)");
Matthew Smith
  • 6,165
  • 6
  • 34
  • 35
-1
$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);
Eric
  • 9,870
  • 14
  • 66
  • 102
  • 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