[英]Search query shows all records when searching in two columns and search word is empty
[英]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.