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?

Recommended Answers

All 2 Replies

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

<?php
require('includes/init_mysql.php');
$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 />";
  }

mysql_close($con);
?>

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');
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.