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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路