1

I am trying to pass a array that contains keys and values.

The keys are columns and values are the values to select.

I am trying to write a function where I can pass a array and use the key and values as the column and values of a table. for example:

$array = array("user"=>"joe", user_id="2");

I need the sql statement to be created like so:

select * from table where $key = $value;
Mat
  • 202,337
  • 40
  • 393
  • 406
Yeak
  • 2,470
  • 9
  • 45
  • 71

2 Answers2

3

You can build a simple SQL Select like so:

<?php


/**
 * @param array Column => Value pairs
 * @return string
 */
function create_sql_select(array $pair){
  $condition = array(); 

  foreach ( $pair as $key => $value){
    $condition[] = "{$key} = '{$value}'";
  } 

 // Separate by AND delimiter if there are more than 1 pair 
 $condition = join(' AND ', $condition);

 // Return prepared string:
 return "SELECT * FROM your_table WHERE {$condition}";
}

//Will print: SELECT * FROM your_table WHERE user = 'some' AND age = '10'
print create_sql_select(array('user' => 'some', 'age' => 10));
Yang
  • 8,580
  • 8
  • 33
  • 58
  • Oh nice approach, better than the function which I currently use for condition mapping. – Fabrício Matté Jun 24 '12 at 22:23
  • Isn't the real escape string function not recommended now. I should mention that I'm using PDO – Yeak Jun 25 '12 at 06:53
  • this code is not using PDO and also it is vulnerable to sql injection – Your Common Sense Dec 05 '16 at 10:54
  • @YourCommonSense This answer is about building a **query string** – Yang Dec 05 '16 at 11:03
  • This **question** is about **PDO**. And of course in its current form this answer is a disaster – Your Common Sense Dec 05 '16 at 11:08
  • @YourCommonSense This question **is not about PDO**. Can you refer exactly where you see it's somehow related to PDO? It's been tagged with PDO, but the question itself is about building a query string. This post answers the original question. Whether it's a best practice to follow - that's another question. So what's your problem here? – Yang Dec 05 '16 at 11:35
  • It's your problem, not mine. this code produces syntactically incorrect SQL and deliberately insecure. – Your Common Sense Dec 05 '16 at 11:42
-1

Use a foreach loop to iterate over the array and get key and value. Like this:

$sql='';
foreach($array as $key=>$value){
    $sql = sprintf("select * from table where %s = %s",$key,$value);
    print $sql;
}
Ander2
  • 5,569
  • 2
  • 23
  • 42