2013-04-22 252 views
0

所以我試圖找出如何搜索多個字段,這裏是我的代碼:搜索多個搜索字詞

 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 [] =「sbody LIKE'%{$ searchTermDB}%'」;.我想知道是如何才能讓在{$ searchTermDB}多個$類型[]像一個例子:

$類型[] = 「sbodystitleslist LIKE '%{$ searchTermDB}%'」 ;

當然,這並不工作,但有什麼辦法,我可以放下的複選框,只是用LIKE「%{$ searchTermDB}%」「搜索所有字段;

+1

你看過MATCH AGAINST嗎? – 2013-04-22 16:53:19

+0

正因如此,你可以參考@KaiQing正在談論的內容:[Match Against](http://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html)。這是你正在尋找的答案。 – 2013-04-22 16:54:19

+0

布爾全文搜索也可以工作:http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html – 2013-04-22 16:55:50

回答

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_函數已棄用

+0

Thankyou,我仍然在制定PDO,並且得到了很好的結果。 – 2013-04-22 17:15:42

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的方法。