【问题标题】:How to execute prepare statement using if statement in PHP PDO?如何在 PHP PDO 中使用 if 语句执行准备语句?
【发布时间】:2020-04-14 11:18:36
【问题描述】:

我正在使用 PHP PDO 准备语句从 MySQL 数据库中获取一些数据。我必须在准备好的语句的执行中使用 if 语句。请参阅下面的代码以更好地理解

$query = "SELECT * FROM my_table WHERE 1=1";

if(isset($_GET['one'])){
    $query .= " AND one = :one";
}

if(isset($_GET['two'])){
    $query .= " AND two = :two";
}

if(isset($_GET['three'])){
    $query .= " AND three = :three";
}

$result = $db->prepare($query);
$result->execute([

    /* ------------------------------------
    How to declare the above parameters here
    as it will show error if any of the if statement is not true? 
    ----------------------------------------*/

]);

我想知道如何在 $result->execute(......]) 块中使用 if 语句声明准备好的数组参数?

【问题讨论】:

    标签: php mysql pdo prepared-statement


    【解决方案1】:

    您需要创建一个空的$params 数组,并且在每个if 块内您可以将适当的值推送给它。例如:

    if(isset($_GET['one'])){
        $query .= " AND one = :one";
        $params[':one'] = $_GET['one'];
    }
    

    那么你可以简单地做

    $result->execute($params);
    

    请注意,您可以根据您编写的内容,在参数名称列表中使用外部 foreach 来简化代码,例如

    $names= array('one', 'two', 'three');
    $params = array();
    foreach ($names as $name) {
        if (isset($_GET[$name])) {
             $query .= " AND $name = :$name";
             $params[":$name"] = $_GET[$name];
        }
    }
    $result->execute($params);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 2010-11-30
      • 2014-04-19
      • 2010-11-18
      相关资源
      最近更新 更多