2009-08-12 63 views
1

我試圖獲取相關文章的列表。示例查找與MySQL LIKE語句相關的文章

$title = $fetch_content[article_name]; // example out put "Hello World, Ask A Question" 
$rel_title = "Select * from tbl_content WHERE status='t' and article_name like '%$title' order by id desc limit 5"; 

如何將「Hello World,Ask A Question」分隔爲單個關鍵字。

+0

小問題:你應該引用數組鍵索引:'$ fetch_content ['article_name']'。不這樣做會使它認爲它是一個常數。 – nickf 2009-08-12 12:11:47

回答

2

可以使用split函數在PHP中打破冠軍成每個單詞:

$title_words = split($title); 

$rel_title = 'select * from tbl_content where status = \'t\' and (1=0'; 

foreach($title as $word) 
{ 
    $word = str_replace(',', '', $word); 
    $word = mysql_real_escape_string($word); 
    $rel_title .= ' or article_title like \'%' . $word . '%\''; 
} 

$rel_title .= ')'; 

echo $rel_title; 

我也用str_replace刪除逗號的問題。顯然,你可以將它應用到其他角色,如果你有。

+0

感謝隊友給我一個線索。你搖滾! – wow 2009-08-12 12:39:40

0

應當指出的是..

like '%$title' 

...只會匹配的項目,如在結束在 '標題',所以你可能想要做...

LIKE '%$title%' 

。 ..如果你只是想要包含'標題'的項目。我也假定$ title變量已經被轉義了。如果沒有,...

LIKE '%" . mysql_real_escape_string($title) . "%'