搜索多个搜索字词

时间:2013-04-22 16:50:24

标签: php mysql

所以我想弄清楚如何搜索多个字段,这是我的代码:

       if (count($error) < 1) {
          $searchSQL = 
"SELECT sid, sdate, stitle, slocation, skategori, stype, sbody, slist FROM job_search WHERE ";

          // grab the search types.
          $types = array();
          $types[] = isset($_GET['title'])?"`stitle` LIKE '%{$searchTermDB}%'":'';
          $types[] = isset($_GET['desc'])?"`skategori` LIKE '%{$searchTermDB}%'":'';
          $types[] = isset($_GET['list'])?"`slist` LIKE '%{$searchTermDB}%'":'';


          $types = array_filter($types, "removeEmpty"); 

          if (count($types) < 1)
             $types[] = "`sbody` LIKE '%{$searchTermDB}%'"; 

          $andOr = isset($_GET['matchall'])?'AND':'OR';
          $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; 

          $searchResult = mysql_query($searchSQL) or trigger_error(
"Error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");

您会注意到我在$ types = array()中使用了一个复选框;如果没有选中复选框,搜索将使用$ types [] =“sbody LIKE'%{$ searchTermDB}%'”;。我想知道的是如何在{$ searchTermDB}中创建多个$ types [],例如:

$ types [] =“sbodystitleslist LIKE'%{$ searchTermDB}%'”;

当然这不起作用,但有没有办法可以删除复选框,只使用LIKE'%{$ searchTermDB}%'搜索所有字段;?

2 个答案:

答案 0 :(得分:0)

SELECT sid, sdate, stitle, slocation, skategori, stype, sbody, slist 
FROM job_search 
WHERE MATCH(`stitle`, `skategori`, `slist`) 
AGAINST('{$searchTermDB}' IN BOOLEAN MODE) 

您可以构建类似于当前操作方式的字段字符串。以上是完整查询的基本示例。

请注意,你真的应该使用像PDO或mysqli这样的东西来处理数据库通信。不推荐使用mysql_函数。

答案 1 :(得分:0)

这是解决方案。完全归功于@Kaiqing的帮助。我放弃了$ types = array();并用以下内容替换:

  // If there are no errors, lets get the search going.
   if (count($error) < 1) {
      $searchSQL = "
      SELECT sid, sdate, stitle, slocation, skategori, stype, sbody, slist 
      FROM job_search 
      WHERE MATCH(`stitle`, `skategori`, `slist`, `sbody`, `slocation`) 
      AGAINST('{$searchTermDB}' IN BOOLEAN MODE) ";

      $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was:        {$searchSQL}");

我没有使用PDO,安全选项是使用PDO方法。