简体   繁体   中英

query works in mysql terminal but not in php

I build my query in PHP dynamically, and when I try to execute it, it fails. When I copy the query it generated and paste it into the mysql terminal and run it, it works fine. The error I get is "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 '>' at line 1" for the following query:

UPDATE events SET event = 'orgo lecture', start = '2014-07-24 16:00:00' WHERE userID = 1 AND eventID = 5

The following is the code used to generate the query dynamically:

$query = "UPDATE events SET ";
$query_list = array();
if ($set_event) {

    $query_list[] = "event = '{$event}'";

}
if ($set_start) {

    $query_list[] = "start = '{$start}'";

}
if ($set_end) {

    $query_list[] = "end = '{$end}'";

}
$query_list_size = count($query_list);
for ($i = 0; $i < $query_list_size - 1; $i++) {

    $query .= $query_list[$i];
    $query .= ", ";

}
$query .= $query_list[$query_list_size - 1];
$query .= " WHERE userID = {$userID} AND eventID = {$eventID}";
echo $query .= "<br />";
$query_result = mysqli_query($connection, $query) or die(mysqli_error($connection));

The echo $query .= "<br />"; instruction is changing the query and making it invalid SQL. Why not use echo $query . "<br />"; echo $query . "<br />"; ?

This issue is this:

echo $query .= "<br />";

Should be

echo $query . "<br />";

Ironically, by checking your query you were breaking it.

As a side note,

$query_list_size = count($query_list);
for ($i = 0; $i < $query_list_size - 1; $i++) {

   $query .= $query_list[$i];
   $query .= ", ";

}
$query .= $query_list[$query_list_size - 1];

Could be shortened to:

 $query .= implode(", ", $query_list);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM