我有以下查询:
$db = static::getDB();
$sql = 'SELECT * FROM media WHERE type = :type AND active = 1
AND title LIKE :term OR artist LIKE :term2 OR label LIKE :term3
ORDER BY date_added DESC';
$stmt = $db->prepare($sql);
$stmt->bindValue(':term', '%' . $term . '%', PDO::PARAM_STR);
$stmt->bindValue(':term2', '%' . $term . '%', PDO::PARAM_STR);
$stmt->bindValue(':term3', '%' . $term . '%', PDO::PARAM_STR);
$stmt->bindValue(':type', 'release', PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
但是问题是WHERE type = :type
子句被完全忽略,并且该请求返回具有所有可用类型的所有匹配记录。
我什至尝试将此变量的bind语句更改为随机的东西,这些东西肯定不是可用的“类型”,但它仍返回所有结果。似乎这种特殊情况已被完全忽略。
最近2个小时我一直在检查并重新检查我的代码,但我在任何地方都看不到任何错误,这是在使用太多LIKE条件时的错误吗?
您有一个运算符优先级问题,OR
低于AND
,因此您的查询将显示所有具有artist LIKE :term2 OR label LIKE :term3
的结果。将这些术语括在括号中以得到预期的结果:
$sql = 'SELECT * FROM media WHERE type = :type AND active = 1
AND (title LIKE :term OR artist LIKE :term2 OR label LIKE :term3)
ORDER BY date_added DESC';