I'm creating a shopping cart, I want when I add a product in cart table then only it should insert at one time. So I'm checking duplicate rows using a column product_code in the table, but this only works for 1st item.....If I click another item add to cart button then It do not insert in the table but it shows message item added instead showing item already added....
action.php
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $conn->prepare("SELECT * FROM product WHERE id=?");
$stmt->bind_param("i",$id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$pname = $row['product_name'];
$pimage = $row['product_image'];
$pprice = $row['product_price'];
$pcode = $row['product_code'];
$pqty = 1;
$stmt2 = $conn->prepare("SELECT product_code FROM cart");
$stmt2->execute();
$res = $stmt2->get_result();
$r = $res->fetch_assoc();
$code = $r['product_code'];
if($pcode!=$code){
$query = $conn->prepare("INSERT INTO cart (product_name,product_price,product_image,qty,total_price,product_code) VALUES(?,?,?,?,?,?)");
$query->bind_param("sssiss",$pname,$pprice,$pimage,$pqty,$pprice,$pcode);
$query->execute();
$_SESSION['showAlert'] = 'block';
$_SESSION['message'] = 'Item added to your cart!';
header("location:index.php");
}
else{
$_SESSION['showAlert'] = 'block';
$_SESSION['message'] = 'Item already added to your cart!';
header("location:index.php");
}
}