我正在使用的查询有问题。
有两个要搜索的内容,一个类别和一个搜索词,类别在我的数据库中的类别列中搜索,但这部分查询仅在选择类别时添加,如果没有,则整个类别部分不存在于查询。
然后我的搜索词在两列中进行搜索,即标题列和文本列(称为 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 else 来查看是否选择了类别(分支)。这段代码:
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)."%'
它有效,但我希望能够搜索数据库中项目的文本和标题。我怎样才能做到这一点?