2012-07-18 69 views
0

我需要在mysql表中搜索某個單詞以在特定列(type:text)中查找。
MySQL搜索

我認爲最簡單的方法就是做:

$str = "something"; # let's say passed by POST or GET from a form 
$sql = "select lala, textThing from table_name where dudu=1 and textThing LIKE %'$str'%"; 

這似乎如果在MySQL做手工查詢工作得很好,但不是通過網絡PHP。 它拋出

您的SQL語法有錯誤;檢查對應於你的MySQL服務器版本在線路附近使用「%searchedString%」正確的語法手冊1

其中searchedString是,嗯,你知道,我搜索了:)

字符串首先PHP看起來是這樣的:

$str = NULL; 


echo "<p>Search for a string</p>"; 
echo "<form name='formSearch' action='result.php' method='post'>"; 
echo "<input type='text' name='text' size='30'/>"; 
echo "<input type='submit' name='search' value='Search'/>"; 
echo "</form>"; 

第二個是剛剛起步的「文本」,做MySQL和應該顯示數據

回答

2

你必須把引號之間的LIKE子句。在你的php代碼中這樣逃脫它們:

$sql = "select lala, textThing from table_name where dudu=1 and textThing LIKE \"%".$str."%\"" 
+0

完美的作品!謝謝! – trainoasis 2012-07-18 15:50:40

+0

以及如果我想要顯示該詞出現在顯示的整個行,該怎麼辦? – trainoasis 2012-07-18 15:53:45

1

你需要在引用或雙引號中包括%。

$ sql =「select lala,textThing from table_name where dudu = 1 and textThing LIKE'%$ str%'」;

$ SQL = 「選擇拉拉,textThing從TABLE_NAME其中嘟嘟= 1和 textThing LIKE '%」 + $ STR + 「%'」;