PHP 从数组生成 sql where 子句

Pao*_*ssi 1 php mysql

我想在我的 php 类中动态地从数组中创建一个 where 子句,其中定义了搜索字段。

$search = array('brand' => 'something', 'model' => 'something');
$myclass->testarr($search);
Run Code Online (Sandbox Code Playgroud)

班级

public function testarr($search){

    if (!empty($search)){

        foreach ($search as $key => $value) {

            $where = $key . " = " . $value;
        }

    $clause = !empty($where) ? 'WHERE' : '';

    $result = $this->db->mysqli->query
    ("SELECT * FROM tb1 $clause $where");

    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是通过输入后缀 AND 来管理具有多个字段的子句。我怎么能这么做呢?谢谢

Mic*_*rin 5

我建议这样做:

$where = array();
if (!empty($search) && is_array($search)) {
    foreach ($search as $key => $value) {
        $where[] = $key . " = " . $value;
    }
}
if (!empty($where))
    $query = sprintf('SELECT * FROM tb1 WHERE %s', implode('AND ', $where));
else
    $query = 'SELECT * FROM tb1';
Run Code Online (Sandbox Code Playgroud)

使用implode使事情变得更容易。

但是要小心逃逸问题,因为您的代码很容易出现安全问题。