I want to post this data from android client and i tested it with postman and status code was 200. But i have a mysqli error and it's:
Error:
((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)
i don't know what is my codes problem and SELECT part works correctly
<?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);
I see 3 possible mistakes.
First mistake, the $id can be empty.
And 2nd mistake can be $likes++ need be ++$likes, because you doesn't sum it with ++ after of the variable, im referring too to --$likes.
The 3rd mistake is your code is vulnerable to MySQL injection, i recommend make a prepared statement.
Link to prepared statement example and explanation: https://www.w3schools.com/php/php_mysql_prepared_statements.asp