如何突出MySQL搜索结果中的关键字

时间:2016-03-08 22:25:52

标签: php mysql

是否有一种简单的方法可以在结果中突出显示搜索到的关键字?该项目是一个博客。搜索功能很有用,但我想强调搜索找到的单词。

这是我的代码:

/*-------------------------  Search    -------------------------------*/  
if(isset($_GET['action']) && $_GET['action'] === 'search'){

    // Connect to database
    include 'includes/dbconnect.php';

    // Check if input box is empty
    if( empty($_GET['search_query']) ){

        $errMsg = 'Please enter data to search.';
        include 'includes/error.html.php';
        exit();       
    } 
    else { 

        // Sanitize user data
        $search = htmlspecialchars($_GET['search_query']);

        // Store $search content into $_SESSIONS['search'] for use below
        $_SESSION['search'] = $search;

    }  

    try {
        $sql = "SELECT post_id, post_category_id, post_title, post_date, post_author, post_keywords, post_image, post_content, cat_title
                FROM posts
                INNER JOIN categories
                ON post_category_id = cat_id
                WHERE post_content LIKE '%$search%'
                OR post_title LIKE '%$search%'
                OR post_author LIKE '%$search%'
                OR post_keywords LIKE '%$search'"; 

        $s = $db->prepare($sql);
        $s->execute();
    } 
    catch (PDOException $e) {
        $errMsg = 'Error fetching data' . $e->getMessage();
        include 'includes/error.html.php';
        exit();
    }

     if($s->rowCount() < 1){
            $errMsg = 'Sorry, no match found for: ' . $_SESSION['search'];
            include 'includes/error.html.php';
            exit();
    } else {

        if($s->rowCount() > 0){
            while($row = $s->fetch(PDO::FETCH_ASSOC)){
                $posts[] = array(
                    'post_id' => $row['post_id'],  
                    'post_category_id' => $row['post_category_id'],
                    'post_title' => $row['post_title'],
                    'post_date' => $row['post_date'],
                    'post_author' => $row['post_author'],
                    'post_keywords' => $row['post_keywords'],
                    'post_image' => $row['post_image'],
                    'post_content' => substr($row['post_content'], 0,240),  //http://php.net/manual/en/function.substr.php
                    'cat_title' => $row['cat_title'],
                );
            }                
        }
    } 

    // Close database connection
    $db = null;

    include 'results.html.php';
    exit();
} 

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

当您创建输出时,请在每个结果中围绕搜索词包装2016-04-09一个适当的类,例如

span

答案 1 :(得分:0)

根据您的查询,您希望在多个字段中查找搜索字符串,但为了提高效率,最好将特定搜索区域组合在一起,如下所示:

$searcharray = [
  $posts['post_title'],
  $posts['post_author'],
  $posts['post_keywords'],
  $posts['post_title']
];

现在要查找要替换的数据,遍历数组并替换它的内容:

foreach($posts as $k => $post){ // loop over main array;
  $searcharray = [
    $posts['post_title'],
    $posts['post_author'],
    $posts['post_keywords'],
    $posts['post_title']
  ];

  foreach($searcharray as $key => $val){ // loop over each post found.
    $posts[$k][$key] = str_replace($search, "<em>$search</em>", $val);
  }
}

旁注:

根据您从数据库中提取的数据量,这可能是瓶颈。你知道吗就个人而言,我最喜欢这样做的方法是让客户自己做。像普通的那样打印出数据并插入包含搜索属性的元素或直接将其打印到Javascript并在特定元素上执行正则表达式来替换客户端的文本。通过这种方式,服务器可以执行与服务器相关的操作,而不是照顾最终用户。

看看this,构建为jQuery的插件并且非常易于使用