doukefu1361 2014-10-04 20:07
浏览 30
已采纳

为什么在预准备语句中计算'like'子句需要括号?

I thought that I'd add a clause similar to the first line of the following to a prepared statement in PHP to run in MySQL:

$sql .= " where ? like '%'+name+'%' ";

if ($stmt = mysqli_prepare($con, $sql)) {    
//irrelevant code omitted here.
} else {
    echo("Error description: " . mysqli_error($con));
}

where name is a column in the table and ? is a parameter to be bound.

I get this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+name+'%' at line 1

If I replace ? with 'fred' and run it in MySQL workbench it will run. Similarly it works if I just remove the concatenation so that it starts $sql .= " where ? like name ";

However if I just change it like so:

? like ('%'+name+'%')

then it runs. Anyone know why please? I ask because I feel that there's something to understand here and I'm not getting it. In particular I'd like to know if there are other scenarios where I'll have to add arbitrary parentheses when using prepared statements?

  • 写回答

2条回答 默认 最新

  • douchun2158 2014-10-04 20:22
    关注

    Use CONCAT(str1,str2,...) to concatenate:

    $sql .= " where ? like CONCAT('%', name, '%')";
    

    + - is addition operator for numbers in MySQL, see: http://dev.mysql.com/doc/refman/5.7/en/arithmetic-functions.html#operator_plus

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?