如何改进搜索功能? PHP + MySQL

时间:2017-11-27 12:54:16

标签: php mysql

我是新来的,我开始用PHP编写代码并使用MySQL 我想在表格中搜索多个“关键字”,例如“Intel i7 7700k”,我不知道如何实现这一目标。

我的MySQL表的结构如下所示:
id | brand | family | model | cores | threads1 | Intel | i7 | 7700k | 4 | 8等。

以下PHP搜索有效,但仅适用于一个单词。

if(isset($_GET['search'])){
  $search = $conn->escape_string($_GET['search']);

  $query = $conn->query("
    SELECT brand, family, model
    FROM cpus
    WHERE brand LIKE '%{$search}%'
    OR family LIKE '%{$search}%'
    OR model LIKE '%{$search}%'
  ");

我试图循环这些单词,但它不起作用。

if(isset($_GET['search'])){
  $search = $conn->escape_string($_GET['search']);
  $words = explode(' ',$search);
  $searchout = foreach ($words as $word){
    "SELECT brand, family, model FROM cpus WHERE brand LIKE '%$word%' OR family LIKE '%$word%' OR model LIKE '%$word%'"
  }
  $query = $conn->query($search_out);

    echo "<div class='result-count'>Found " . $query->num_rows . " results.</div>";

    if($query->num_rows){
      while($r = $query->fetch_object()){

        echo "<div class='result'><a href='#'>" . $r->brand . $r->model . "</a></div>";
      }
    }
}  

如何使搜索能够处理多个单词? 像"Intel i7 7700k" "7700k intel i7" "i7 7700k intel"

这是我的另一次尝试也失败了:

if(isset($_GET['search'])){
  $search = $conn->escape_string($_GET['search']);
  $words = explode(' ',$search);
  $words_count = count($words);
  $cpus_columns = ['brand','family','model'];
  print_r($cpus_columns);
  $mysql_where = "SELECT brand, family, model FROM cpus WHERE ".$cpus_columns[0]." LIKE ".$words[0];
  $mysql_loop = for ($i = 1; $i <= $words_count; $i++){
    " OR ".$cpus_columns[$i]." LIKE ".$words[$i]
  }
  $mysql_query = $mysql_where . $mysql_loop;
  $query = $conn->query($mysql_query);

    echo "<div class='result-count'>Found " . $query->num_rows . " results.</div>";

    if($query->num_rows){
      while($r = $query->fetch_object()){

        echo "<div class='result'><a href='#'>" . $r->brand . $r->model . "</a></div>";
      }
    }
}

我开始慢慢讨厌PHP和MySQL,4天而且无法让它工作这只是悲伤。

0 个答案:

没有答案