Multi word search in PHP/MySQL

前端 未结 4 1473
故里飘歌
故里飘歌 2020-12-03 16:43

I\'m struggling to create a search that searches for multiple words. My first attempt yielded no results whatsoever and is as follows:

  require_once(\'datab         


        
4条回答
  •  时光取名叫无心
    2020-12-03 16:51

    here's what i did

    if (isset($_POST['search'])){
    $words = mysql_real_escape_string($_POST['searchfield']);   
    $arraySearch = explode(" ", trim($words));       
    $countSearch = count($arraySearch);
    $a = 0;
    $query = "SELECT * FROM parts WHERE ";
    $quote = "'";
    while ($a < $countSearch)
    {
      $query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
      $a++;
      if ($a < $countSearch)
      {
        $query = $query." AND ";
        }   
      }
        $result=mysql_query($query) or die(error);
    

    //you could just leave it here, short and sweet but i added some extra code for if it doesnt turn up any results then it searches for either word rather than boths words//

    $num = mysql_num_rows($result);
    if ($num == 0){
     $a = 0;
     $query = "SELECT * FROM parts WHERE ";
    while ($a < $countSearch)
    {
      $query = $query."description LIKE $quote%$arraySearch[$a]%$quote ";
      $a++;
      if ($a < $countSearch)
      {
        $query = $query." OR ";
        $msg = "No exact match for: $words. Maybe this is what you're looking for though? If not please try again.";
        }
    
      }
      }
      $result=mysql_query($query) or die($query);
      if (mysql_num_rows($result) == 0){
        $msg = "No results, please try another search";
        }
    
    }
    

提交回复
热议问题