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

时间:2015-10-21 08:38:39

标签: php mysql

我有一些代码生成一个名为 $ query 的MySQL查询字符串:

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

返回类似于:

的内容

从调查中选择*,其中surveylayoutid =' 12'和customerid =' 1'和(邮政编码如'%dn%')按ID desc排序

工作正常。我之后改变了代码,因为我想搜索更多字段,现在它显示为:

$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;
 }
}

这也会返回:

从调查中选择*,其中surveylayoutid =&#39; 12&#39;和customerid =&#39; 1&#39;和(邮政编码如&#39;%dn%&#39;)按ID desc排序

在它的表面上是相同的,但它会产生这个错误:

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便使用&#39;%dn%&#39;由id desc&#39;命令在第1行

在这两种情况下,$ query包含相同的&#34; text&#34;但由于某些原因,在更新的代码中没有被视为有效的MySQL查询,有人可以告诉我为什么吗?

2 个答案:

答案 0 :(得分:1)

一个可能的问题可能是这里对内容的解释。 如果您使用:

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

“...”内的所有内容都将被解释。因此,乍一看你可能会看到不必要的副作用,并且可以解释正在发生的事情。为避免这种情况,必须将其更改为:

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

即使在它有多大的方面更加笨拙,但它确保$ lue和%不被解释为''之间的所有'不被解释。

答案 1 :(得分:0)

看看这是否有助于您解决问题?

$remap = array(
    "Postcode",
    "Street",
    "HouseNum",
    "District",
    "Town"
);

for ($i = 0; $i <= 4; $i++)
    {
    if ($_POST[strtolower($remap[$i]) ] != "")
        {
        $query = "select * from Surveys where surveylayoutid='12' and customerid='1' and (";
        $clue = $_POST[strtolower($remap[$i]) ];
        $query.= $remap[$i] . " like '%$clue%') order by id desc";
        $query_done[] = $query;
        unset($query);
        $result = mysql_query($query_done[$i], $connection) or die(mysql_error());

        // Display your result here

        }
    }

我尝试更改你的代码abit,似乎结果是这样的

select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%Postcode%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Street like '%Street%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (HouseNum like '%HouseNum%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (District like '%District%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Town like '%Town%') order by id desc