【问题标题】:How to build an Ajax search bar with multiple keywords?如何构建具有多个关键字的 Ajax 搜索栏?
【发布时间】:2016-05-27 12:58:19
【问题描述】:

我尝试构建一个 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 = "SELECT title, description, picture FROM outfit WHERE type LIKE '%$input%' OR color LIKE '%$input%' OR brand LIKE '%$input%' OR material LIKE '%$input%'";怎么样

标签: javascript mysql ajax database


【解决方案1】:

假设您的关键字被“空格”分隔,例如“ABC DEF GEH”。

你可以做的比在服务器上,

$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.")";

【讨论】:

【解决方案2】:

这样的?当然,所有 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);

【讨论】:

  • 谢谢,但我还是没能成功...它没有考虑第二个关键字...如果我搜索黑色连衣裙,它将输出黑色的所有内容.. .也许我的数据库有错误,但我刚刚创建了一个简单的数据库,其中每列都在同一个表上。所以..我会继续努力。
  • 请您粘贴它为“black”、“dress”生成的最终 SQL 查询吗?
猜你喜欢
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 2015-01-16
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多