Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
434 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...