Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
<?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
// Render The Cart For The User To View
$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.
Posted
Comments
Killzone DeathMan 20-Jan-14 11:09am    
Man, all its working fine!
When I add the second item it is NOT starting again!
MaddyDesigner 21-Jan-14 3:12am    
Cool then.
I must have made mistake somewhere then..
Anyways, thanks for your help.
Killzone DeathMan 21-Jan-14 9:46am    
hahaha lol xD

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900