我试图建立一个ajax搜索栏。单个关键字可以很好地工作,但我无法让它与2个关键字一起工作...
我当时正在考虑解析输入字段中的数据,但是我的知识有限,而且我没有设法找到解决方案。
有任何想法吗?
在我的main.js中,我从输入中获取数据,如下所示:
var kwVal = $(this).val();
if (kwVal.length < 3){
$(".clothes-container").html("");
}
else {
$.ajax({
"url": "ajax/getclothes.php",
"type": "GET",
"data": {
"kw": kwVal
}
})
这是我的SQL请求
$sql = "SELECT title, description, picture
FROM outfit
WHERE type LIKE :keyword OR
color LIKE :keyword OR
brand LIKE :keyword OR
material LIKE :keyword";
非常感谢。
最佳答案
像这样吗当然,所有SQL文字和字符串都必须正确转义(尤其是$keyword
)。
// keywords extracted from user's input
$keywords = array('blue', 'jeans');
// columns, that You want to match against
$columns = array('type', 'color', 'brand', 'material');
// we build the condition for each keyword
$word_conditions = array();
foreach ($keywords as $keyword) {
$conditions = array();
foreach ($columns as $column)
$conditions[] = $column.' LIKE \'%'.$keyword.'%\'';
$word_conditions[] = '('.implode(' OR ', $conditions).')';
}
// we build the query, that requires every item to have all the keywords
$query = 'SELECT * FROM ... WHERE '.implode(' AND ', $word_conditions);