Searching across multiple columns

冷暖自知 提交于 2019-12-13 09:10:55

问题


I'm trying to make a search feature that will search multiple columns to find a keyword based match. For example when the user enters a keyword to search, i need to conduct a search across five category columns and return the corresponding row names of all the rows that contain the keyword in either of its category columns. The code is as follows:

   <?php
    mysql_connect($dbhost, $dbuser, $dbpass) or die("could not connect.");
  mysql_select_db($dbname) or die("could not find database.");
  $result = "";
  //collect info from database
  if(isset($_POST['search'])) {
      $searchq = $_POST['search'];
      $searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
//SQL query
      $query = mysql_query("SELECT name FROM institutes WHERE category1 LIKE '%$searchq%' OR category2 LIKE '%$searchq%' OR category3 LIKE '%$searchq%' OR category4 LIKE '%$searchq%' OR category5 LIKE '%$searchq%'") or die("No records found.");
      $count = mysql_num_rows($query);
      if($count == 0)
      {
          $output = "There's no search result";
      }
      else {
          while($array = mysql_fetch_assoc($query))
    {
    ?>
        <li><?php echo $array['name'];?></li>
    <?php
    }
  ?>
      }
  }
  </ul>

I have tried various ways to search but every time, either there is an error or the code just returns every row name irrespective of conditions. a solutions to the problem will be appreciated.


回答1:


<?php
    mysql_connect($dbhost, $dbuser, $dbpass) or die("could not connect.");
  mysql_select_db($dbname) or die("could not find database.");
  $result = "";
  //collect info from database
  if(isset($_POST['search'])&& $_POST['search'] != "")) {
      $searchq = $_POST['search'];
      $searchq = preg_replace("#[^0-9a-z]#i","",$searchq);

//SQL query
      $query = mysql_query("SELECT name FROM institutes WHERE category1 LIKE '%".$searchq."%' OR category2 LIKE '%".$searchq."%' OR category3 LIKE '%".$searchq."%' OR category4 LIKE '%".$searchq."%' OR category5 LIKE '%".$searchq."%'");
      $count = mysql_num_rows($query);
      if($count == 0)
      {
          $output = "There's no search result";
      }
 else {
          while($row= mysql_fetch_assoc($query))
            {

             echo $row['name'];

            }

      }
  }
  ?>


来源:https://stackoverflow.com/questions/36371155/searching-across-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!