Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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;
share|improve this question
    
Are you using PDO, mysqli or mysql to execute the query? – Fabrício Matté Jun 24 '12 at 22:17
    
I'm using PDO to execute. – Yeak Jun 25 '12 at 6:52
up vote 3 down vote accepted

This is what you want:

<?php


/**
 * @param array for WHERE clause
 * @return string
 */
function sql_select(array $pair){
  //just init cond array:
  $condition = array(); 

  foreach ( $pair as $key => $value){
    //oh yeah, you can also automatically prevent SQL injection  
    $value = mysql_real_escape_string($value);

    $condition[] = "{$key} = '{$value}'";
  } 

 //Prepare for WHERE clause: 
 $condition = join(' AND ', $condition);
 //Return prepared string:
 return "SELECT * FROM your_table WHERE {$condition}";
}

//print: SELECT * FROM your_table WHERE user = 'some' AND age = '10'
print sql_select(array('user' => 'some', 'age' => 10));

This is called ORM approach.

share|improve this answer
    
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 6:53
    
Works great thank you so much. – Yeak Jun 25 '12 at 16:26

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;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.