【问题标题】:construct conditional SQL statement with PDO用 PDO 构造条件 SQL 语句
【发布时间】:2015-08-30 13:22:44
【问题描述】:

当依赖于是否设置了某些 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 语句?

【问题讨论】:

    标签: php mysql sql pdo


    【解决方案1】:

    我会使用一个数组来包含 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);
    

    【讨论】:

    • 是的,构造查询可能会更优雅——但是我怎么知道我需要在执行语句中绑定什么?
    • 不是 100%,但看起来像执行关联数组...请参阅已编辑答案中的代码。
    • 这在大多数情况下都可以使用,但是应该有条件地添加 WHERE 子句,因为 variableN 可能都不包含值。
    • 我完全同意零...实际上 $query 永远不需要设置如果 count($arrWhere)
    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多