如何使用多个关键字构建Ajax搜索栏?

时间:2016-02-16 10:01:01

标签: javascript mysql ajax database

我尝试构建一个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";

非常感谢。

2 个答案:

答案 0 :(得分:0)

这样的东西?当然,必须正确转义所有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);

答案 1 :(得分:0)

假设您的关键字是由空间&#39;喜欢&#34; ABC DEF GEH&#34;。

而不是服务器,你可以做到,

$keywords = explode(" ", $_POST['data']); //Make it array;
$string = implode(",", $keywords);

$sql = "SELECT title, description, picture
    FROM outfit 
    WHERE type in (".$string.") OR
          color in (".$string.") OR
          brand in (".$string.") OR
          material in (".$string.")";