我有一个代码可以使用 ajax 动态搜索数据库中的数据,但我一次只能搜索 1 个关键字.我想修改它以便我可以搜索多个关键字.现在,如果我输入2个用空格隔开的关键字,在数据库中,数据没有用空格隔开,则不会有结果.如果数据库中的数据是:
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'
然后我搜索:
游戏站
不会有结果.我想知道是否可以修改我的代码,以便我可以搜索 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>";
}
动态搜索所有关键字,可以使用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:在您的查询中使用用户输入之前,请务必对其进行转义.
Note 1: Always escape user input before using it in your query.
注意 2: mysql_* 函数已弃用,请使用 Mysqli 或 PDO 作为替代
Note 2: mysql_* functions are deprecated, use Mysqli or PDO as an alternative
2018 年更新 - 注意 3: 不要忘记检查 $queried 变量的长度并设置限制.否则,用户可能会输入一个不同的大字符串并导致您的数据库崩溃.
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模板网!
在 SELECT(MYSQL/PHP) 中加入 2 个表Joining 2 tables in SELECT(MYSQL/PHP)(在 SELECT(MYSQL/PHP) 中加入 2 个表)
如何使<option selected=“selected">由How to make lt;option selected=quot;selectedquot;gt; set by MySQL and PHP?(如何使lt;option selected=“selectedgt;由 MySQL 和 PHP 设置?)
使用 PHP 中的数组自动填充选择框Auto populate a select box using an array in PHP(使用 PHP 中的数组自动填充选择框)
PHP SQL SELECT where like search item with multiple wordsPHP SQL SELECT where like search item with multiple words(PHP SQL SELECT where like search item with multiple words)
json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT(json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8)
MySQL ORDER BY rand(),名称 ASCMySQL ORDER BY rand(), name ASC(MySQL ORDER BY rand(),名称 ASC)