【发布时间】:2021-04-20 12:59:37
【问题描述】:
有人可以帮助/建议我如何在 sql 查询中使用 if 语句吗? 我正在尝试创建一个搜索表单,其中查询只会考虑“类别”和“类型”字段(如果它们不为空)?
我已尝试以下代码,但收到错误消息:
public static function findBySearch($data)
{
$location = $data['location'];
$category = $data['category'];
$type = $data['type'];
$sql = 'SELECT * FROM posts
WHERE location = :location';
if ($category != '') {
$sql .= ', category = :category';
}
if ($type != '') {
$sql .= ', type = :type';
}
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':location', $location, PDO::PARAM_STR);
if ($category !='') {
$stmt->bindValue(':category', $category, PDO::PARAM_STR);
}
if ($type !='') {
$stmt->bindValue(':type', $type, PDO::PARAM_STR);
}
return $stmt->execute();
}
错误:
Uncaught exception: 'PDOException'
Message: 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' category = 'To Rent', type = 'House'' at line 2'
Stack trace:
#0 C:\xampp\htdocs\findingproperty\App\Models\Post.php(269): PDOStatement->execute()
#1 C:\xampp\htdocs\findingproperty\App\Controllers\Posts.php(106): App\Models\Post::findBySearch(Array)
#2 [internal function]: App\Controllers\Posts->searchAction()
#3 C:\xampp\htdocs\findingproperty\Core\Controller.php(51): call_user_func_array(Array, Array)
#4 C:\xampp\htdocs\findingproperty\Core\Router.php(121): Core\Controller->__call('search', Array)
#5 C:\xampp\htdocs\findingproperty\public\index.php(63): Core\Router->dispatch('posts/search')
#6 {main}
我们将不胜感激。
【问题讨论】:
-
你缺少逻辑运算符。多个条件不是由逗号链接,而是由运算符
AND和OR链接。 -
@El_Vanja 感谢您的回复。您能否建议添加逻辑运算符的正确方法是什么(我尝试在 if 语句之前添加 AND 运算符,但收到语法错误:“unexpected AND”)?
-
停下来想一想。如果您的 PHP
if条件没有得到满足,而您最终只有一个 SQL 条件怎么办?在查询结束时,您将有一个悬空的AND。仅当您的 PHP 条件满足时才应添加它 - 即在其中。 -
@El_Vanja,非常感谢。我已经按照下面的方法更新了 if 语句,它现在运行良好。感谢您的帮助 - 非常感谢。
-
if ($category != '') { $sql .= ' AND category = :category'; } if ($type != '') { $sql .= ' AND type = :type'; }