PHP从数组生成sqlwhere子句


PHP generate sql where clause from array

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

$search = array('brand' => 'something', 'model' => 'something');
$myclass->testarr($search);

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

我的问题是通过输入后缀AND来管理一个包含多个字段的子句。我怎么能那样做?感谢

我建议这样做:

$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';

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

但是要注意转义问题,因为您的代码容易出现安全问题。

您的代码有一个缺陷:$where = $key . " = " . $value;将在每次迭代中覆盖$where,您需要使用.=进行连接。然后可以这样做,例如

$where = "";
foreach ($search as $key=>$value) {
    if (!empty($where)) $where .= " AND ";
    $where .= $key . " = " . $value;
}
$clause = !empty($where) ? 'WHERE '.$where : '';

这将在每个条件之前添加一个AND,从第二个条件开始(因为对于第一个条件,if将失败)。

我建议研究准备好的语句,这些语句将使您的代码更加安全,一旦您理解了这个概念,它们就会变得非常容易处理(imo)。因为如果这是您目前的大部分代码,那么您很容易受到SQL注入的攻击。