Hello,
Am making an online shop where users can buy the products. While making it, am getting an error.
The error is that when the user presses the button on add to cart, the cart doesn't show up with the quantity, I mean the exact quantity, because when I add 1 product to the cart, it adds perfectly but when I add second product, it starts again from 1 and I don't know the reason behind it.
Here's the source code of the cart.php page =>
<?php
session_start();
?>
<?php
if (isset($_POST['pid'])) {
$id = $_POST['pid'];
$wasFound = false;
$i = 0;
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
$_SESSION["cart_array"] = array(
1 => array(
"item_id" => $id, "quantity" => 1
)
);
} else {
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $id) {
array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $id, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
}
}
}
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $id, "quantity" => 1));
}
}
}
?>
<?php
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
unset($_SESSION["cart_array"]);
}
?>
<?php
$cartOutput = "";
$total_items = 0;
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
$cartOutput = "<h2 align='center'>Your Shopping Cart Is Empty.</h2>";
} else {
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
$cartOutput .= "<h2>Cart Item " . $i . "</h2>";
while (list($key, $value) = each($each_item)) {
$cartOutput .= $key . " : " . $value . "<br />";
}
}
}
?>
Kindly guide me where I am making the mistake so that I can rectify it.
Thanks.
MaddyDesigner.