php mysql原生查询构造like,如何在MySQL LIKE查询中使用PHP字符串?

I am trying to find the number of rows that match a specific pattern. In this example, all that START with "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:

$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'%'");

解决方案

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 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);

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值