如何在 mySQL LIKE 查询中使用 PHP 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10133450/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:27:59  来源:igfitidea点击:

How to use PHP string in mySQL LIKE query?

phpmysqlsqlstring

提问by JROB

I am trying to find the number of rows that match a specific pattern. In this example, all that START with "123":

我试图找到匹配特定模式的行数。在此示例中,所有以“123”开头的内容:

This is working:

这是有效的:

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '123%'");
$count = mysql_num_rows($query);

The problem is the LIKE will vary, so I'm trying to define it in the script, then execute the query, but this is NOT working:

问题是 LIKE 会有所不同,所以我试图在脚本中定义它,然后执行查询,但这不起作用:

$prefix = "123";
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix.'%'");
$count = mysql_num_rows($query);

How can I get this query to work properly in the second example?

我怎样才能让这个查询在第二个例子中正常工作?

EDIT: I've also tried it without the period (also not working):

编辑:我也试过没有句号(也不起作用):

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix'%'");

回答by Jon

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

你的语法错误;无需在双引号字符串中放置句点。相反,它应该更像是

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

您可以通过打印出字符串来确认它是否与第一种情况相同。

Of course it's not a good ideato simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

当然,像这样简单地将变量注入查询字符串并不是一个好主意,因为存在 SQL 注入的危险。至少你应该用 手动转义变量的内容mysql_real_escape_string,这将使它看起来像这样:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintfthe percent sign needs to be doubled to end up appearing once in the result.

请注意,sprintf百分号的第一个参数需要加倍才能在结果中出现一次。

回答by Starx

DO it like

喜欢

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the %at the end

别忘%了最后