I build a cart for an ecommerce website, and I want to know if I did well.
I want to record the changes in the DB and display the information from the DB to the customer. To be sure that what he sees is the good information. I use an ajax request and JSON to do so.
Please give me your comments. I especially want to know is my code safe?
The client side:
function save_to_db(cartId, newQuantity) {
$.ajax({
url: "updateCart.php",
data: "cartId=" + cartId + "&newQuantity=" + newQuantity + "&memberId=" + <?php echo $memberId?>,
type: 'post',
dataType: "json",
success: function(response) {
if (response === "Empty cart") {
$("#total-quantity").text(0);
$("#total-price").text(0);
$("#shopping-cart-table").html("<h2><b style='color:red'>Your cart is empty.</b></h2>");
}
if (newQuantity == 0) {
$("#item-container-" + cartId).remove();
}
var totalQuantity = 0;
var totalItemPrice = 0;
$.each(response, function(key, cartDetails) {
totalItemPrice = totalItemPrice + parseInt(cartDetails.price) * parseInt(cartDetails.quantity);
totalQuantity = totalQuantity + parseInt(cartDetails.quantity);
if (cartDetails.cartId == cartId) {
$("#input-quantity-" + cartId).val(cartDetails.quantity);
$("#cart-price-" + cartId).text("$" + cartDetails.price * cartDetails.quantity);
}
});
$("#total-quantity").text(totalQuantity);
$("#total-price").text(totalItemPrice);
$("#total-price-foot").text(totalItemPrice);
}
});
}
The server side:
<?php
require 'connectDB.php';
$memberId = $_POST["memberId"];
if($_POST["newQuantity"] == 0){
$stmt = mysqli_prepare($conn,"DELETE FROM tbl_cart WHERE id = ? AND member_id = ?");
mysqli_stmt_bind_param($stmt, "ii", $_POST["cartId"], $memberId);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
elseif ($_POST["newQuantity"] == 1 || $_POST["newQuantity"] == -1) {
$stmt = mysqli_prepare($conn,"UPDATE tbl_cart SET quantity =
(CASE WHEN quantity + ? > 0 THEN quantity + ? ELSE quantity END)
WHERE id= ? AND member_id = ?");
mysqli_stmt_bind_param($stmt, "iiii",
$_POST["newQuantity"],
$_POST["newQuantity"],
$_POST["cartId"],
$memberId);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
if ($stmt = mysqli_prepare($conn,"SELECT tbl_product.id, tbl_product.price, tbl_cart.quantity, tbl_cart.id
AS cartId FROM tbl_product, tbl_cart WHERE tbl_product.id = tbl_cart.product_id AND tbl_cart.member_id = ?")) {
mysqli_stmt_bind_param($stmt, "i", $memberId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)){
$cartDetails[] = $row;
}
mysqli_stmt_close($stmt);
}
if(isset($cartDetails)){
$response = json_encode($cartDetails);
echo $response;
}
else{
$response = json_encode("Empty cart");
echo $response;
}
?>