How to get values from array to create SQL statement

Hi fellas,

I have the following array:

$where = array(“name”=>“Gerep”, “password”=>“123”);

And I’m creating a SQL statement and this array must be placed as the WHERE condition.

I need to get the result: SELECT * FROM user WHERE name = “Gerep” AND password = “123”

How can I do that?!

Thanks in advance

Thanks to everyone but I’m gonna stick with AnthonySterling’s solution.

$where = array(“name”=>“Gerep”, “password”=>“123”);

foreach($where as $key=>$value){
if($count==0) $whr_string .= $key.‘="’.$value.‘"’;
else $whr_string .= ’ AND ‘.$key.’=“‘.$value.’”';

echo “SELECT * FROM user WHERE $whr_string”;

I’d use [fphp]vsprintf/fphp.

$sql = vsprintf(
    "SELECT id FROM table WHERE username = '&#37;s' AND password = '%s' AND role = '%s' LIMIT 1",

However, just in-case you’re actually looking for prepared statements, take a look at PDO.


Unless you need to loop through the values? In which case I would suggest the foreach loop =)

$sql = "SELECT * FROM user WHERE name = '{$where['name']}' AND password = '{$where['password']}'";
  • May want to escape values (perhaps already escaped?)