使用 php 和 mysql 搜索多个关键字(其中 X 喜欢)

search for multiple keywords with php and mysql (where X like)(使用 php 和 mysql 搜索多个关键字(其中 X 喜欢))
本文介绍了使用 php 和 mysql 搜索多个关键字(其中 X 喜欢)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个代码可以使用 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 喜欢)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Difference between mt_rand() and rand()(mt_rand() 和 rand() 的区别)
Coalesce function for PHP?(PHP的合并函数?)
Fastest way to convert string to integer in PHP(在 PHP 中将字符串转换为整数的最快方法)
2 Column Mysql Date Range Search in PHP(PHP中的2列Mysql日期范围搜索)
mysql match against ~ example(mysql 匹配 ~ 示例)
How-to: Ranking Search Results(操作方法:对搜索结果进行排名)