[英]construct conditional SQL statement with PDO
取決於是否設置了一些PHP變量時,用PDO構造SQL語句的最佳方法是什么?
這是一個例子;
$query="SELECT * FROM table ";
if($variable1 != "") { $query = $query . "WHERE variable1 = :variable1"; }
if($variable2 != "") { $query = $query . " AND variable2 = :variable2"; }
$query -> execute(array(':variable1' => $variable1, ':variable2' => $variable2));
我有很多這些if
語句,當將變量綁定到查詢時,我不想再次經歷所有這些if
語句。
有沒有更簡單的方法來構建具有此類if / else條件的SQL語句?
我將使用一個數組來包含where的每個部分。當發生匹配時,將結果語句添加到數組中。 評估完后,進行內爆,以“ AND”分隔並連接到$ query上。
$arrWhere = array();
$assWhere = array();
if($variable1 != "") {
$arrWhere[] = "variable1 = :variable1";
$assWhere[":variable1"] = $variable1;
}
if($variable2 != "") {
$arrWhere[] = "variable2 = :variable2";
$assWhere[":variable2"] = $variable2;
}
if($variable3 != "") {
$arrWhere[] = "variable3 = :variable3";
$assWhere[":variable3"] = $variable3;
}
$query="SELECT * FROM table WHERE " . implode ( " AND " , $arrWhere );
$query -> execute($assWhere);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.