簡體   English   中英

PHP從數組生成SQL where子句

[英]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 = $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注入的攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM