【问题标题】:how to use keywords in searchengine如何在搜索引擎中使用关键字
【发布时间】:2012-09-10 17:17:40
【问题描述】:

你好,我坐在这里思考以下问题:

我有一个自动建议搜索引擎,它通过如下表格运行:

zipcode    city       sum

12345      town       5

我确实通过使用 javascript 来实现搜索,该 javascript 在将要输入的每个字母上运行一个循环。到目前为止,我只能寻找一个关键字,例如可以是城市名称或邮政编码。

现在我想将这两者结合起来,这样我就不再将用户限制为这两者之一,即使输入城市和邮政编码也会找到它。

因此,我想使用以下方法分隔每个关键字:

preg_split('/[\s]+/', $keywords);

这是目前的问题。使用这种方法,每个关键字都将被插入到一个数组中。它是如何工作的:

在 html 中我有一个输入字段。下面我有一个无序列表 div。在那个 div 中,javascript 会自动添加我的 search.php 文件中的结果。看起来像:

include('../scripts/db_connect.php');

if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {

$search_term = $db->real_escape_string(htmlentities(trim($_POST['search_term'])));

$search_term_query = "SELECT * FROM `a` WHERE `b` LIKE '$search_term%'";

if ($result_query = $db->query($search_term_query)) {

    while ($row = $result_query->fetch_assoc()) {

    echo '<li>', 
          $row["a"], 
          ' ', 
          $row["b"],  
          ' ',
          '( ',
          $row["c"],
          ' )', 
          ' </li>';
    }

}

}

我的 javascript 只处理一个关键字:

$(document).ready(function() {
    $('.searchfield').keyup(function() {
        var search_term = $(this).attr('value');
        $.post('ajax/search.php', {search_term:search_term}, function(data) {
            $('.result').html(data);

            $('.result li').click(function() {
                var result_value = $(this).text();
                $('.searchfield').attr('value', result_value);
                $('.result').html('');
            });
        });
    });
});

所以目前我不知道如何解决这个问题。如果有人可以帮助我,我真的很感激。谢谢。

【问题讨论】:

标签: php html loops mysqli search-engine


【解决方案1】:

只需保持原样并通过 post 调用将整个字符串发送到您的 php 文件。 在您的 search.php 中,您可以尝试这样的操作:

function split_search_term($val) {
    $val = explode(" ", $val);
    $search_term_query = "SELECT * FROM `a` WHERE ";
    foreach($val as $val_row) {
        $search_term_query .= "(`zipcode` LIKE '" . $search_term . "%' OR `city`  LIKE '" . $search_term . "%') OR ";
    }
    if(count($val) > 0) {
        // The IF statement is used to make sure that the foreach loop has been fired at least once,
        // or else it would just chop off the 'WHERE ' part and you'll get something like:
        // "SELECT * FROM `a` WH" and this will give you an error
        $search_term_query = substr($search_term_query, 0, -4); // To cut off the last remaining ' OR ' in the query
    } else {
        $search_term_query .= "0"; // To finish the query so it doesn't return anything we don't want
    }

    return $search_term_query;
}

您可以从这里继续获取结果。我希望它有效。

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2010-11-23
    • 2011-07-24
    • 2011-10-15
    • 2011-06-08
    相关资源
    最近更新 更多