跨多列搜索 [英] Searching across multiple columns

查看:56
本文介绍了跨多列搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个搜索功能,该功能将搜索多个列以查找基于关键字的匹配项.例如,当用户输入要搜索的关键字时,我需要在五个类别列中进行搜索,并返回在其任一类别列中包含该关键字的所有行的相应行名称.代码如下:

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.

推荐答案

<?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'];

            }

      }
  }
  ?>

这篇关于跨多列搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆