如何在php pdo中使用if语句执行prepare语句?

问题描述 投票:0回答:1

我正在使用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个回答
0
投票

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

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

然后您可以简单地做

$result->execute($params);
© www.soinside.com 2019 - 2024. All rights reserved.