有几种方法。一种方法是动态构建 SQL 文本。如果选项是离散的,我们可以单独处理每个条件,包括或不包括。作为模式的示例:
开始 SQL 文本:
$sql = "SELECT ...
FROM ...
WHERE 1=1 ";
有条件地附加搜索条件
if( we need to add a condition on city ) {
$sql .= " AND t.city LIKE :city ";
}
if( we need to add a condition on province ) {
$sql .= " AND t.province LIKE :province ";
}
if( we need to add a condition on name ) {
$sql .= " AND t.name LIKE :name ";
}
完成 SQL 文本
$sql .= " ORDER BY ...";
准备 SQL 文本(这里是 echo/var_dump/log $sql 的内容进行调试的好地方)
$sth = $dbh->prepare($sql);
为我们添加的任何搜索条件有条件地绑定值
if( we need to add a condition on city ) {
$sth->bindValue(':city',$city);
}
if( we need to add a condition on province ) {
$sth->bindValue(':province',$province);
}
if( we need to add a condition on name ) {
$sth->bindValue(':name',$name);
}
执行
$sth->execute();
另一种选择是在 WHERE 子句中使用带有表达式的静态 SQL,使用“特殊”保留值来表示“不搜索”。
在本例中,我们使用长度为零的字符串表示“无搜索条件”...
$sql = "SELECT ...
FROM ... t
WHERE ( :city1 = '' OR t.city LIKE :city2 )
AND ( :province1 = '' OR t.province LIKE :province2 )
AND ( :name1 = '' OR t.name LIKE :name2 )
ORDER BY ...";
$sth = $dbh->prepare($sql);
$sth->bindValue(':city1' , $city );
$sth->bindValue(':city2' , $city );
$sth->bindValue(':province1' , $province );
$sth->bindValue(':province2' , $province );
$sth->bindValue(':name1' , $name );
$sth->bindValue(':name2' , $name );
$sth->execute();