drm30963 2015-10-21 08:38
浏览 51
已采纳

PHP构建的字符串中的MySQL语法错误

I have some code which generates a MySQL query string called $query:

$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
$clue = $_POST['postcode'];
$onwhat="Postcode";
$query .= $onwhat . " like '%$clue%') order by id desc";
$result = mysql_query($query, $connection) or die(mysql_error());

This returns something like:

select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc

which works fine. I've then altered the code because I want to search on more fields so it now reads:

$remap = array("Postcode", "Street", "HouseNum", "District", "Town");
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
for ($i=0; $i<=4; $i++) {
 if ($_POST[strtolower($remap[$i])]!="") {
  $clue = $_POST[strtolower($remap[$i])];
  $query .= $remap[$i] . " like '%$clue%') order by id desc";
  break;
 }
}

This also returns:

select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc

which on the face of it is identical but it generates 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 'like '%dn%' order by id desc' at line 1

In both cases $query contains the same "text" but for some reason isn't treated as a valid MySQL query in the updated code, can anyone tell me why?

  • 写回答

2条回答 默认 最新

  • dtip91401 2015-10-21 09:43
    关注

    One possible problem could be the interpretation of the content here. If you use:

      $query .= $remap[$i] . " like '%$clue%') order by id desc";
    

    All that is inside "" gets to be interpreted. Thus there could be unwanted side effects that you don't see at first glance and can explain what is happening. To avoid this it would have to be changed to:

    $query .= $remap[$i] . ' like ' . "'" . '%' . $clue . '%' . "') order by id desc";
    

    Even though more clunky in terms of how big it is, it makes sure that $lue and also the % are not interpreted as all in between ' ' is not interpreted.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题