2012-12-18 102 views
1

當我搜索一個詞「蘋果」的劇本是顯示按以下順序結果:如何重新排序搜索結果?

(1)蘋果樹 (2)juiceapple (3)蘋果

但我要重新排序的搜索結果按以下順序:

(1)蘋果 (2)蘋果樹 (3)juiceapple

正如你可以看到上面的命令正是我想其中的結果顯示根據SE拱形的術語,是 「蘋果」

//get date 
$button = $_GET['submit']; 
$search = $_GET['search']; 

if (!$button) 
    echo "Please fill out the form"; 
else 
{ 
    if (strlen($search)<=2) 
    echo "The item you searched for was to small"; 
    else 
    { 
    echo "You searched for <b>$search</b> <hr size='1'>"; 

    //connect to database 

    mysql_connect('localhost','wnumber','passowrd'); 
    mysql_select_db('wnumber'); 


//explode search term 
      $search_exploded = explode(" ",$search); 
      foreach($search_exploded as $search_each) 
{ 
    $str = mysql_real_escape_string(substr($search_each, 0, 4)); 
    //construct query 
    $x++; 
    if ($x==1) $construct .= "keywords LIKE '$str%'"; 
    else  $construct .= " OR keywords LIKE '$str%'"; 
} 




    //echo out construct 
    $construct = "SELECT * FROM word WHERE $construct"; 
    $run = mysql_query($construct); 
    $foundnum = mysql_num_rows($run); 

    if ($foundnum==0) 
     echo "No results found."; 
    else 
    { 

     echo "$foundnum results found.<p><hr size='1'>"; 

     while ($runrows = mysql_fetch_assoc($run)) 
     { 


     //get data 
     $meaning = $runrows['meaning']; 
     $keywords = $runrows['keywords']; 

     echo "<b>$keywords</b><br> 
     <b>$meaning</b><br> 

     } 

    } 



    } 
} 
+1

使用LIKE'蘋果%'不符合juiceapple,但'%蘋果%'將做 –

回答

1

除了升序如果你對長度的關注意味着嘗試LENGTH()

$construct = "SELECT * FROM word WHERE $construct order by LENGTH(`keywords`) 
+0

但如果'關鍵字'列包含多個關鍵字,則會顯示具有較少關鍵字(關鍵字列最短值)的行 – Buksy

2

使用ORDER BY ASC

$構建= 「SELECT * FROM字,其中$構建ORDER BY [要從提升你的搜索字段名稱] ASC」 ;

+0

我替換行但頁面顯示錯誤警告:mysql_num_rows()期望param eter 1是資源,布爾在59給出 – user1835767

+1

@ user1835767嘗試... $ con = mysql_connect('localhost','wnumber','passowrd'); mysql_select_db('wnumber',$ con); 而不是 mysql_connect('localhost','wnumber','passowrd'); mysql_select_db('wnumber'); – Abhi

+0

@ user1835767添加到你的行來自我自己的查詢,它在這裏工作正常。您在** [您想要提升您的搜索的字段名稱]中輸入了什麼值** – freaky

1

使用ORDER BY keywords ASC它會給你預期的結果。

2

嘗試

ORDER BY關鍵字升序

爲了得到期望的結果

1

我假設你有多行關鍵字。您正在獲取所有這些結果,因爲您正在搜索包含單詞apple的任何單詞。

首先要獲得準確的結果,然後只包含單詞的結果,像這樣做:

  1. 搜索結果相符完全字「apple」
  2. 搜索任何該結果包含單詞「apple」

由於每行有多個關鍵字,因此不能使用=運算符。但是您必須在表格中使用一些separator以將關鍵字彼此分開。我們假設它的「」(空格)。

所以,如果你的表和列的「關鍵詞」是這樣的,例如

| id | name | keywords | 
| 1 | apple | apple fruit sweet | 

可以搜索這樣的結果:

SELECT * FROM table t1 
WHERE 
keywords LIKE "% $keyword %" /* Notice whitespaces around the variable */ 
OR 
keywords LIKE "$keyword %" /* This is for keywords that arent separated from left */ 
OR 
keywords LIKE "% $keyword" /* This is for keywords that arent separated from right */ 

UNION DISTINCT /* Distinct is there because we want to show every result just once */ 

SELECT * FROM table t1 
WHERE 
keywords LIKE "%$keyword%" 

PS:分離器可以是任意的字符串或字符,它不必是空白