2014-01-16 228 views
0

即時嘗試編碼搜索引擎。
除此之外,如果我輸入一個查詢如西海岸,我也得到東海岸的結果。發生這種情況是因爲東部和西部的關鍵字包含海岸作爲單個詞。PHP搜索引擎錯誤

但是我想用這行代碼到單獨的兩個:

<?php 
$k = $_GET['k']; 
$terms = explode(" ", $k); 
$query = "SELECT * FROM Search WHERE "; 
foreach ($terms as $each){ 
    $i++; 

    if($i == 1) 
     $query .= "keywords LIKE '%$each%' "; 
    else 
     $query .= "OR keywords LIKE '%$each%' "; 

} 

如果我回應了這一點用在搜索表單中的關鍵字都走散了,但進一步對他們不
如何我能解決這個問題嗎?

<?php 
$k = $_GET['k']; 
$terms = explode(" ", $k); 
$query = "SELECT * FROM Search WHERE "; 
foreach ($terms as $each){ 
    $i++; 

    if($i == 1) 
     $query .= "keywords LIKE '%$each%' "; 
    else 
     $query .= "OR keywords LIKE '%$each%' "; 

} 
if($k == "" || $k == " ") 
{ 
    echo "<p> Please enter a valid search term."; //If search is empty or contains only a space. 
    exit; 
} 
//connect to database 
mysql_connect("LOCALHOST" ,"ROOT" ,"PASSWORD"); 
mysql_select_db("DATABASE"); 
$query = mysql_query($query); 
$numrows = mysql_num_rows($query); 
if($numrows > 0){ 
    while($row = mysql_fetch_assoc($query)) 
    { 
     $id = $row['id']; 
     $title = $row['title']; 
     $description = $row['description']; 
     $keywords = $row['keywords']; 
     $link = $row['link']; 
     echo "<h2><a href ='$link' class='searchcolor' color='#a8a8a8'> $title</a></h2> 
      $description<br /> 
      This page contains information about \"<b>$query</b>\"<br /><hr>"; 
    } 

} 
else 
    echo "No results for \"<b>$k</b>\""; 

//disconnect 
mysql_close(); 


?> 
+0

使用MATCH(),而不是像這樣MATCH(「東海岸」),它返回一個加權的搜索結果,因此您可以按相關性排序,即:東海岸擁有高於相關性因此您可以確保東海岸出現在頂部和西岸,出現在第200頁上。注意,這僅適用於全文索引和myiasm表格。你可以用innodb表來做,但你必須在代碼中做而不是查詢。 – Dave

回答

0

您的疑問:

SELECT * FROM Search WHERE keywords LIKE '%west%' OR keywords LIKE '%$coast%'; 

將返回匹配,因爲OR的這些關鍵字的要麼其結果。如果您希望結果匹配所有關鍵字,請使用AND

I.e.改變

$query .= "OR keywords LIKE '%$each%' "; 

$query .= "AND keywords LIKE '%$each%' "; 
+0

這真的幫助我了! 謝謝! – brian

+0

@brian沒問題。樂意效勞。 – Jim