how do i run a query for a variable with multiple values?

i've been told a loop is not the right way to do it, which is the way i've been doing it and it has worked. I assumed putting it in a foreach loop would accomplish looping the query for variable with multiple values.

e.g. testa and testb are both in the array, $key.
foreach($key as $value) {

//mysql query


How do i run a single query not in a loop that will have both 'testa' and 'testb' in the WHERE clause?

Edited by MDanz: n/a

7 Years
Discussion Span
Last Post by mwasif

You only need one query which you run once. Then you fetch the results into an array and loop over the array.

$con = mysql_connect($db_host,$db_user,$db_pass);
if (!$con)
  die('Could not connect: ' . mysql_error());

mysql_select_db("daniweb", $con);

$key = array('Cable Guy', 'John Doe');
foreach($key as $value){
    $dr[] = "name = '$value' "; // Build array of strings
$sql = "SELECT * FROM people WHERE ";
$sql .= implode(' OR ', $dr); // convert to string joined by ' OR ' and add to end of $sql

// Instead of using a loop and running a query for 'Cable Guy'
// and another query for 'John Doe', the following query fetches both rows.
$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
  echo $row['name'] . " " . $row['dob'];
  echo "<br />";


Edited by d5e5: Remembered way to build sql string dynamically


An alternative can be use of IN e.g the following query will return the results where usernames are user1 or user2.

SELECT * FROM table WHERE username IN ('user1','user2');

Edited by mwasif: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.