我正在使用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);
请注意,您可以根据编写的内容,在参数名称列表中使用外部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);