Here is a simple PHP code that implements an API that clears the cart items:
<?php
// Include confi.php
include_once('conn.php');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$userID = isset($_POST['userID']) ? mysqli_real_escape_string($conn, $_POST['userID']) : "";
// Clear cart against the userid
$sql = "delete from cart where userID = '". $userID ."' ";
$qur = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if ($qur) {
$json = array("ClearCart" => "success");
} else {
$json = array("ClearCart" => "fail");
}
} else {
$json = array("status" => 0, "ClearCart" => "Expected POST request.");
}
mysqli_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
PROBLEM:
In either case where the cart is cleared or not the message: "ClearCart" => "success"
is what is seen in Postman response. The functionality is working but the correct clause is not getting executed.
CodePudding user response:
The affected_rows / mysqli_affected_rows() function returns the number of affected rows in the previous SELECT, INSERT, UPDATE, REPLACE, or DELETE query
Syntax: mysqli_affected_rows(connection);
This returns, the number of rows affected (could be 0 or above). also, -1 indicates that the query has returned an error.
Try to update your code this way,
if (mysqli_affected_rows($conn) > 0) {
$json = array("ClearCart" => "success");
} else {
$json = array("ClearCart" => "fail");
}