php MySQL 查询字符串包含
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2602252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL query String contains
提问by arik
I've been trying to figure out how I can make a query with MySQL that checks if the value (string $haystack) in a certain column contains certain data (string $needle), like this:
我一直试图弄清楚如何使用 MySQL 进行查询,以检查$haystack某个列中的值 (string )是否包含某些数据 (string $needle),如下所示:
mysql_query("
SELECT *
FROM `table`
WHERE `column`.contains('{$needle}')
");
In PHP, the function is called substr($haystack, $needle), so maybe:
在 PHP 中,该函数被调用substr($haystack, $needle),所以可能:
WHERE substr(`column`, '{$needle}')=1
回答by Wolph
Quite simple actually:
其实很简单:
mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");
The %is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.
的%是用于设置任何字符(无,一个或多个)的通配符。请注意,这在非常大的数据集上可能会变慢,因此如果您的数据库增长,您将需要使用全文索引。
回答by OMG Ponies
回答by chris
WHERE `column` LIKE '%$needle%'
回答by risnandar
Mine is using LOCATEin mysql:
我LOCATE在 mysql 中使用:
LOCATE(substr,str), LOCATE(substr,str,pos)
定位(substr,str),定位(substr,str,pos)
This function is multi-byte safe, and is case-sensitive only if at least one argument is a binary string.
此函数是多字节安全的,并且仅当至少一个参数是二进制字符串时才区分大小写。
In your case:
在你的情况下:
mysql_query("
SELECT * FROM `table`
WHERE LOCATE('{$needle}','column') > 0
");
回答by Joshua Powell
In addition to the answer from @WoLpH.
除了@WoLpH 的回答。
When using the LIKEkeyword you also have the ability to limit which direction the string matches. For example:
使用LIKE关键字时,您还可以限制字符串匹配的方向。例如:
If you were looking for a string that starts with your $needle:
如果您正在寻找以您的开头的字符串$needle:
... WHERE column LIKE '{$needle}%'
If you were looking for a string that ends with the $needle:
如果您正在寻找以 结尾的字符串$needle:
... WHERE column LIKE '%{$needle}'
回答by Andres
You probably are looking for find_in_setfunction:
您可能正在寻找find_in_set功能:
Where find_in_set($needle,'column') > 0
This function acts like in_arrayfunction in PHP
此函数的作用类似于in_arrayPHP 中的函数
回答by Alejandro Moreno
be aware that this is dangerous:
请注意,这是危险的:
WHERE `column` LIKE '%{$needle}%'
do first:
先做:
$needle = mysql_real_escape_string($needle);
so it will prevent possible attacks.
所以它会阻止可能的攻击。

