使用数组键和值来创建sql select语句

时间:2022-10-05 07:55:44

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:

我需要像这样创建sql语句:

select * from table where $key = $value;

2 个解决方案

#1


4  

You can build a simple SQL Select like so:

您可以像这样构建一个简单的SQL Select:

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

#2


0  

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

使用foreach循环迭代数组并获取键和值。喜欢这个:

$sql='';
foreach($array as $key=>$value){
    $sql = sprintf("select * from table where %s = %s",$key,$value);
    print $sql;
}

#1


4  

You can build a simple SQL Select like so:

您可以像这样构建一个简单的SQL Select:

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

#2


0  

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

使用foreach循环迭代数组并获取键和值。喜欢这个:

$sql='';
foreach($array as $key=>$value){
    $sql = sprintf("select * from table where %s = %s",$key,$value);
    print $sql;
}