php数组中where条件的生成

m1m5dgzv  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(280)

我有一个关联数组,比如

$where = array('name'=>'name','comp'=>'companyname')

这是我的问题

select * from tablename where = $where;

我想让mysqli查询生成

select * from tablename where name = 'name' and comp = 'companyname';
qyswt5oh

qyswt5oh1#

echo "select * from tablename where ".implode(' AND ' , preg_replace('/^(.*)$/e', ' "$1=\'". $where["$1"]."\'" ',array_flip($where)));
q5lcpyga

q5lcpyga2#

试试这个。我在字符串中设置条件,并将字符串附加到查询的末尾。如果设置where to be 1=1+“yourstuff”,则可以动态构建查询。

$queryappnd = '';
foreach($where as $i){
    $column = array_key($i);
    $value = $i;
    $queryappnd .='AND'.$column.'='.$value;
}

$query = "SELECT *
          FROM tablename
          WHERE 1=1".$queryappnd;

相关问题