我正在使用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语句声明准备好的数组参数?
希望您已理解我的问题。热情等待您的回答。谢谢。
您需要创建一个空的$params
数组,并且可以在每个if
块内向其推送适当的值。例如:
if(isset($_GET['one'])){
$query .= " AND one = :one";
$params[':one'] = $_GET['one'];
}
然后您可以简单地做
$result->execute($params);