我想在我的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使事情变得更容易。

但是请当心转义问题,因为您的代码容易出现安全问题。

关于php - PHP从数组生成SQL where子句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20422353/

10-14 16:05
查看更多