繁体   English   中英

当搜索字符串为空时,带有连接的搜索查询会显示所有行

[英]search query with join shows all rows when searched string is empty

我有一个查询要在两个表中搜索空缺职位。

此查询的变量与具有多个输入/选择的表单一起发送。 一个是空缺标题的文本输入,另一个是包含空缺可以属于的所有类别的下拉列表。

当我将文本输入留空并仅选择一个类别时,我会获得所有空缺,而不仅仅是来自所选类别的空缺。

我的查询:

$functie = $_POST['functie'];
$branche = $_POST['branche'];
$regio = $_POST['regio'];

$search = "
SELECT cnt.title, cnt.alias, cnt.images, cnt.introtext, cnt.catid, cat.title, cat.alias
FROM snm_content cnt
LEFT JOIN snm_categories cat
ON cat.id = cnt.catid
WHERE ('".$functie."' ='' OR cnt.title LIKE '%".$functie."%')
OR ('".$branche."' ='' OR cat.title LIKE '%".$branche."%')
";

如果我在不输入文本输入的情况下回显查询,这就是我得到的:

SELECT cnt.title, cnt.alias, cnt.images, cnt.introtext, cnt.catid, cat.title, cat.alias
FROM snm_content cnt
LEFT JOIN snm_categories cat
ON cat.id = cnt.catid
WHERE ('' ='' OR cnt.title LIKE '%%')
OR ('logistiek' ='' OR cat.title LIKE '%logistiek%')

snm_content是空缺, snm_categories是类别。

如何仅显示属于所选类别的职位空缺?

请注意,您的代码对SQL 注入相关的攻击是开放的。 请学会使用Prepared Statements

现在,我们需要动态生成查询的WHERE部分。 我们可以使用!empty()函数检查输入的过滤器值是否不为空,然后动态地将其条件添加到查询中。

$functie = $_POST['functie'];
$branche = $_POST['branche'];
$regio = $_POST['regio'];

$search = "
SELECT cnt.title, cnt.alias, cnt.images, cnt.introtext, cnt.catid, cat.title, cat.alias
FROM snm_content cnt
LEFT JOIN snm_categories cat
ON cat.id = cnt.catid ";

// Collect all the where conditions in an array
$whr = array();

// check if $functie has some value in input filter
if (!empty($functie)) {
    $whr[] = "cnt.title LIKE '%" . $functie . "%'";
}

// check if $branche has some value in input filter
if (!empty($branche)) {
    $whr[] = "cat.title LIKE '%" . $branche . "%'";
}

$where_sql = '';
// Prepare where part of the SQL
if (!empty($whr)) {

    $where_sql = ' WHERE ' . implode(' OR ', $whr);
}

// Append to the original sql
$search .= $where_sql;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM