問題描述
我有一個代碼可以使用 ajax 動態(tài)搜索數(shù)據(jù)庫中的數(shù)據(jù),但我一次只能搜索 1 個關鍵字.我想修改它以便我可以搜索多個關鍵字.現(xiàn)在,如果我輸入2個用空格隔開的關鍵字,在數(shù)據(jù)庫中,數(shù)據(jù)沒有用空格隔開,則不會有結(jié)果.如果數(shù)據(jù)庫中的數(shù)據(jù)是:
I have a code that dynamically search for data in the database using ajax but I can search for only 1 keyword in a time. I would like to modify it so I can search for multiple keywords. Now, if I type 2 keywords separated by a space and in the database, the data is not separated by a space, there will be no result. If in the database the data is:
'playstation3' 或 'play cool station3'
'playstation3' or 'play cool station3'
然后我搜索:
游戲站
不會有結(jié)果.我想知道是否可以修改我的代碼,以便我可以搜索 2 個或更多關鍵字或單詞,這些關鍵字或單詞由空格或另一個單詞、點或下劃線或 (-) 或 (+) 或 (%) 分隔或(其他任何東西,哈哈).
there would be no results. I would like to know if it possible to modify my code so I can search 2 or more keywords or words separated by a space or another word or a DOT or an underscore or a (-) or a (+) or a (%) or (anything else lol).
我知道我應該使用 pdo 或 mysqli,但我僅將其用于測試!
I know that I should use pdo or mysqli but i'm using this for testing only!
$queried = $_POST['query'];
$search = mysql_query("SELECT * FROM links WHERE name LIKE '%$queried%'");
while($searche = mysql_fetch_array($search)){
echo "".$searche['link']."</br>".$searche['name']."</br>".$searche['size']."</br>".$searche['category']."<hr></br></br>";
}
推薦答案
動態(tài)搜索所有關鍵字,可以使用explode功能將所有關鍵字分開;
To dynamically search all keywords, you can use the explode function to seperate all keywords;
$queried = mysql_real_escape_string($_POST['query']); // always escape
$keys = explode(" ",$queried);
$sql = "SELECT * FROM links WHERE name LIKE '%$queried%' ";
foreach($keys as $k){
$sql .= " OR name LIKE '%$k%' ";
}
$result = mysql_query($sql);
注意 1:在您的查詢中使用用戶輸入之前,請務必對其進行轉(zhuǎn)義.
Note 1: Always escape user input before using it in your query.
注意 2: mysql_* 函數(shù)已棄用,請使用 Mysqli 或 PDO 作為替代
Note 2: mysql_* functions are deprecated, use Mysqli or PDO as an alternative
2018 年更新 - 注意 3: 不要忘記檢查 $queried
變量的長度并設置限制.否則,用戶可能會輸入一個不同的大字符串并導致您的數(shù)據(jù)庫崩潰.
Update 2018 - Note 3: Don't forget to check the length of the $queried
variable and set a limit. Otherwise the user can input a vary large string and crash your database.
這篇關于使用 php 和 mysql 搜索多個關鍵字(其中 X 喜歡)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!