我收到 mysqli 错误 1064,但我不知道为什么

I got mysqli error 1064 but i don't know why

我想 post 来自 android 客户端的数据,我用 postman 测试了它,状态代码是 200。但是我有一个 mysqli 错误,它是:

错误:

((1064) 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 'WHERE id=' at line 1)

我不知道我的代码有什么问题,SELECT 部分工作正常

<?php


$id = $_POST['id'];
$isLiked = $_POST['isLiked'];


if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


$connection = mysqli_connect($host, $username, $password, $database);
$query = "SELECT likes FROM posts WHERE id=$id";
$result = mysqli_query($connection, $query);



$array = mysqli_fetch_assoc($result);
$likes = $array['likes'];

if ($isLiked == true) {

    $updateQuery = "UPDATE posts SET likes=" . $likes++ . " WHERE id=$id";

} else {

    $updateQuery = "UPDATE posts SET likes=" . $likes-- . " WHERE id=$id";

}


if (!$connection->query($updateQuery)) {
    echo "query failed: (" . $connection->errno . ") " . $connection->error;
}

mysqli_query($connection, $updateQuery);
if (!$connection->query($updateQuery)) {
    echo "query failed: (" . $connection->errno . ") " . $connection->error; // It returns that 1064 error
}

mysqli_query($connection, $updateQuery);

我看到了 3 个可能的错误。

第一个错误,$id 可以为空

而第二个错误可能是 $likes++ 需要 ++$likes,因为你没有在变量之后用 ++ 求和,我也指的是 --$likes.

第三个错误是您的代码容易受到 MySQL 注入攻击,我建议制作一个 准备好的语句

Link 到 准备语句 示例和解释:https://www.w3schools.com/php/php_mysql_prepared_statements.asp