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

编程入门 行业动态 更新时间:2024-10-27 04:24:19
本文介绍了如何在MySQL LIKE查询中使用PHP字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试查找与特定模式匹配的行数.在此示例中,所有以"123"开头的内容:

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

这有效:

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

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

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:

$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?

我也试过了没有句号(也无法使用):

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

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

推荐答案

语法错误;无需在双引号字符串内放置句点.相反,它应该更像

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.

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

Of course it's not a good idea to 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 = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'", mysql_real_escape_string($prefix)); $query = mysql_query($sql);

请注意,在sprintf的第一个参数内,百分号需要加倍以最终在结果中出现一次.

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

更多推荐

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

本文发布于:2023-10-28 05:33:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   如何在   MySQL   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!