搜索查询显示在两列中并且搜索词为空时显示所有记录

时间:2018-12-11 07:46:35

标签: php sql database mysqli

我正在使用的查询有问题。

要搜索的东西有两个,一个类别和一个搜索词,在我的数据库的一个类别列中进行类别搜索,但是只有在选择了一个类别时才添加查询的这一部分,如果没有,则整个类别部分为查询中不存在。

然后我的密码输入了两个列,分别是标题列和文本列(称为introtext)。

这是我现在的查询

$content = "
SELECT cnt.id as content_id, cnt.title as content_title, cnt.featured, cnt.ordering, cnt.alias as content_alias, cnt.catid, cnt.images, cnt.state, cnt.introtext, cat.id as cat_id, cat.title as cat_title, cat.alias as cat_alias,
MAX(case when f.field_id = 7 then f.value end) as hoofdafbeelding,
MAX(case when f.field_id = 8 then f.value end) as openingstijden,
MAX(case when f.field_id = 9 then f.value end) as straat,
MAX(case when f.field_id = 10 then f.value end) as facebook,
MAX(case when f.field_id = 11 then f.value end) as instagram,
MAX(case when f.field_id = 12 then f.value end) as telefoonnummer,
MAX(case when f.field_id = 13 then f.value end) as website
FROM snm_categories cat
LEFT JOIN snm_content cnt
ON cnt.catid = cat.id AND cnt.state = 1
LEFT JOIN snm_fields_values f
ON cnt.id = f.item_id
WHERE cnt.title LIKE '%".$conn->real_escape_string($trefwoord)."%' OR
cnt.introtext LIKE '%".$conn->real_escape_string($trefwoord)."%'
".$branchequery."
GROUP BY cnt.id, cnt.title, cnt.featured, cnt.alias, cnt.catid, cnt.images, cnt.state, cnt.introtext, cat.id, cat.title, cat.alias
ORDER BY cnt.ordering";
$contentcon = $conn->query($content);

在此之上,我还有另外两个if来查看是否选择了类别(分支)。这段代码:

if(!empty($branche)){
  $branchequery = "AND cat.alias LIKE '".$conn->real_escape_string($branche)."'";
}else{
  $branchequery = '';
}
$branchetitel = str_replace('-', ' ', $branche);
if(!empty($trefwoord)){
  $gezocht = 'Je zocht naar: <b class="orange">'.$trefwoord.'</b>';
}else if(empty($trefwoord) AND empty($branche)){
  $gezocht = 'Je hebt geen zoekopdracht ingevoerd.';
  $branchequery = "AND cat.alias LIKE '%.............%'";
}else{
  $gezocht = 'Je zocht naar: <b class="orange">'.ucfirst($branchetitel).'</b>';
}

这些点是一个肮脏的解决方法,因此我的查询为空时不会返回所有行。

但是当$trefwoord为空时,我仍然遇到这个问题。

因此,当我在搜索表单中选择一个类别但不添加搜索词($ trefwoord)时,我仍然会获得所有行,而不仅仅是该类别中的项目,我会全部获得。

我该如何解决?

以某种方式,如果我从查询中删除此行:

OR
    cnt.introtext LIKE '%".$conn->real_escape_string($trefwoord)."%'

它可以工作,但是我希望能够在数据库中搜索项目的文本和标题。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您的问题出在WHERE子句中的运算符优先级上。目前,当$trefwoord为空时,您的WHERE子句如下:

WHERE cnt.title LIKE '%%' OR
      cnt.introtext LIKE '%%' AND 
      cat.alias LIKE 'something'

这被评估为

WHERE cnt.title LIKE '%%' OR
      (cnt.introtext LIKE '%%' AND cat.alias LIKE 'something')

这将始终为真(cnt.title LIKE '%%'将始终匹配)。您需要通过适当地使用括号来解决此问题,因此WHERE子句看起来像

WHERE (cnt.title LIKE '%%' OR cnt.introtext LIKE '%%') AND 
      cat.alias LIKE 'something'

因此,在您的PHP中编写:

WHERE (cnt.title LIKE '%".$conn->real_escape_string($trefwoord)."%' OR
cnt.introtext LIKE '%".$conn->real_escape_string($trefwoord)."%')
".$branchequery."