我创建了一个包含复选框的搜索表单,用户选择复选框,然后过滤掉显示的结果。
目前它在某种程度上可以工作,但是,由于“AND”语句,它返回 0 个结果。
例如
举个例子,我的数据库有一个名为“vibes”的列,我有 2 条记录,
name | vibes
Brunch1 | Party Animal, Music Maniac, Arty
Brunch2 | Arty, Party Animal
假设用户已选中 Party Animal、Arty 的复选框
它返回“Brunch 1 和 Brunch2”,但是如果用户选择 Touristy
复选框并提交表单,它会返回 0 个结果,因为它会检查 Brunch1
和Brunch2
在共鸣栏中有 Touristy
。
我假设它与添加 AND 语句有关,这就是单击“提交”后 SQL 查询当前的样子...
SELECT b.*, host FROM brunches b LEFT JOIN hosts ON hosts.id =
b.hostid WHERE approved ='1' AND vibes LIKE '%Arty%' AND vibes LIKE
'%Party Animal%' AND vibes LIKE '%Touristy%'
我的PHP代码
$brunches = "SELECT b.*, host
FROM brunches b
LEFT JOIN hosts ON hosts.id = b.hostid ";
$conditions = array();
$conditions[] = "approved ='1'";
if(! empty($vibes)) {
foreach($vibes as $tag):
$conditions[] = "vibes LIKE '%$tag%'";
endforeach;
}
$sql = $brunches;
if (count($conditions) > 0) {
$sql .= " WHERE " . implode(' AND ', $conditions);
}
$sql= $this->db->query($sql);
我相信这是因为它使用 AND 而不是 OR,
但是,我在搜索表单中还有其他字段,例如“名称”,因此确实要求它类似于 WHERE name = '' ANDroved = '1' AND vivi= ''
等
希望这是有道理的。
最佳答案
您可以在 where
子句中添加已批准的 = 1 作为硬编码,在括号中添加 like
部分并通过 OR
链接,而不是和
。我还移动了将 WHERE
添加到 if
中的部分,该部分创建了 conditions
值...
$sql = $brunches;
if(! empty($vibes)) {
$conditions = [];
foreach($vibes as $tag) {
$conditions[] = "vibes LIKE '%$tag%'";
}
$sql .= PHP_EOL."WHERE approved ='1' and (" . implode(' OR ', $conditions).")";
}
它会生成类似...的东西
SELECT b.*, host
FROM brunches b
LEFT JOIN hosts ON hosts.id = b.hostid
WHERE approved ='1' and (vibes LIKE '%a%' OR vibes LIKE '%b%')
关于php - 创建了一个搜索表单,该表单向 SQL 查询添加了条件,但由于 'AND' 语句而返回 0 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312289/