我正在尝试创建一个搜索脚本来搜索数据库中的汽车并匹配用户输入的所有关键字。如果我将关键字文本框留空并搜索我得到结果,但如果我输入任何关键字,我得不到结果。
header('x-my-header: whatever');
更新:
现在可以改变它但是如果我搜索$search_keywords = $_POST['search_keywords'];
$terms = $search_keywords;
$items = explode(' ',$terms);
$types = array();
foreach ($items as $item) {
$types[] = "'title' LIKE '%{$item}%'";
$types[] = "'exterior_colour' LIKE '%{$item}%'";
}
$sql = "SELECT * FROM list_car WHERE ";
$sql .= implode(" && ", $types) . " ORDER BY 'title'";
$result = mysqli_query($link, getPagingQuery($sql, $rowsPerPage));
所有Toyota hilux dfkjodsgfudsugfdsgfgfgfdgfdg
都会出现,但是Toyota hilux
是垃圾而未列在数据库中我希望它匹配所有关键字而不是只有一个或多个。
dfkjodsgfudsugfdsgfgfgfdgfdg
答案 0 :(得分:2)
您应该使用OR
(||
)代替AND
(&&
)。实际上,您的搜索字词必须与所有字段匹配:
$sql = "SELECT * FROM list_car WHERE ";
$sql .= implode(" OR ", $types) . " ORDER BY 'title'";
答案 1 :(得分:1)
以下是我的表现。
$terms = $search_keywords = 'Toyota hilux dfkjodsgfudsugfdsgfgfgfdgfdg';
$items = explode(' ',$terms);
$types = array();
$sql = "SELECT * FROM list_CAR WHERE ";
foreach ($items as $item) {
$sql .= " (`title` LIKE ? or `exterior_colour` LIKE ?) and ";
$params[] = '%' . $item . '%';
$params[] = '%' . $item . '%';
}
if(!empty($params)) {
$sql = rtrim($sql, ' and ');
$result = mysqli_prepare($link, $sql);
foreach($params as $param) {
mysqli_stmt_bind_param($result, "s", $param);
}
mysqli_stmt_execute($result);
} else {
die('No params built...WHY');
}
注意我使用未经测试的mysqli
预处理语句,我还没有在mysqli
中按程序构建参数化查询,我将此方法基于{{3}上的用户评论}。
这应该提供诸如
之类的查询SELECT * FROM list_CAR
WHERE
(`title` LIKE ? or `exterior_colour` LIKE ?) and
(`title` LIKE ? or `exterior_colour` LIKE ?) and
(`title` LIKE ? or `exterior_colour` LIKE ?)
这将要求每个关键字都出现在标题或颜色列表中。
如果你要保持毫无准备,这是不受推荐和不良的做法,那就是..
$terms = $search_keywords = 'Toyota hilux dfkjodsgfudsugfdsgfgfgfdgfdg';
$items = explode(' ',$terms);
$types = array();
foreach ($items as $item) {
$types[] = " (`title` LIKE '%{$item}%' or `exterior_colour` LIKE '%{$item}%') ";
}
$sql = "SELECT * FROM list_CAR WHERE ";
$sql .= implode(" and ", $types) . "";
echo $sql;
输出:
SELECT * FROM list_CAR WHERE
(`title` LIKE '%Toyota%' or `exterior_colour` LIKE '%Toyota%') and
(`title` LIKE '%hilux%' or `exterior_colour` LIKE '%hilux%') and
(`title` LIKE '%dfkjodsgfudsugfdsgfgfgfdgfdg%' or `exterior_colour` LIKE '%dfkjodsgfudsugfdsgfgfgfdgfdg%')