您的 SQL 语法有误 - PHP MYSQL

You have an error in your SQL syntax - PHP MYSQL

我有以下代码:

$combined = array_combine($idArray, $sumsArray);
    //print_r($combined);

foreach ($combined as $key => $value) {

        $sqlToUpdate .= "UPDATE tbl_test SET ing_ml='".$value."' WHERE ing_id=".$key.";";

    if(isset($_POST['update'])){

        if ($conn->query($sqlToUpdate) === TRUE) {
            echo "Record updated successfully<br /><br />";
        } else {
            echo "Error updating record: " . $conn->error . "<br /><br />";
        }
    }
}
echo $sqlToUpdate;

echo $sqlToUpdate; 的输出是:

UPDATE tbl_test SET ing_ml='-5' WHERE ing_id='22';UPDATE tbl_test SET ing_ml='-1' WHERE ing_id='19';UPDATE tbl_test SET ing_ml='9' WHERE ing_id='13';UPDATE tbl_test SET ing_ml='0' WHERE ing_id='11';UPDATE tbl_test SET ing_ml='5' WHERE ing_id='4';

如果我复制此输出,并 运行 直接在 phpMyAdmin 中执行,它会完美执行,并且所有 5 行都已更新。

但是,当我尝试从 PHP 页面执行它时(单击更新按钮,因此 "if isset")我收到以下错误:

Record updated successfully

Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tbl_test SET ing_ml='-1' WHERE ing_id='19'' at line 1

Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tbl_test SET ing_ml='-1' WHERE ing_id='19';UPDATE tbl_test SET ing_ml='9'' at line 1

Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tbl_test SET ing_ml='-1' WHERE ing_id='19';UPDATE tbl_test SET ing_ml='9'' at line 1

Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tbl_test SET ing_ml='-1' WHERE ing_id='19';UPDATE tbl_test SET ing_ml='9'' at line 1

因此,foreach 中的第一个查询执行良好并更新了数据库,但其余 4 个查询失败。我已经尝试了一切,但无法弄清楚这是为什么。我尝试在 $value 周围以及 $value 和 $key 周围添加反引号、单引号等,但似乎没有任何效果。

使用准备好的语句!

$combined = array_combine($idArray, $sumsArray);

$stmt = $conn->prepare("UPDATE tbl_test SET ing_ml=? WHERE ing_id=?");
$stmt->bind_param("ss", $value, $key);
foreach ($combined as $key => $value) {
    $stmt->execute();
}
echo "Record updated successfully<br /><br />";

您的 $conn->query($sqlToUpdate)foreach 循环中,并且您的 $sqlToUpdate 变量在此循环中通过 .= 递增。

每次循环,你都是re-executing以前的查询。