小编典典

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

sql

我试图传递包含键和值的数组。

键是列,值是要选择的值。

我试图编写一个函数,可以传递数组并将键和值用作表的列和值。例如:

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

我需要这样创建sql语句:

select * from table where $key = $value;

阅读 481

收藏
2021-03-10

共1个答案

小编典典

您可以构建一个简单的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));
2021-03-10