Click here to Skip to main content
15,900,818 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Am trying to make a mini shopping cart where the user can buy goods.
Everything's working fine but when I check out, only the second product in the cart gets loaded in the check out option and not the first product, this means if the cart has only 1 product, it works well and good, but when added second product, it takes the second product and not the first one. Please correct me where am making mistake.

Here's the code I have done so far:
PHP
<?php
// Session Start
session_start();
include 'storescripts/dbconnect.php';

?>
<?php
// Add To The Cart
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(
									0 => 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));
		}
	}
	header("Location: cart.php");
	exit();
}
?>
<?php
// Empty The Cart
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
	unset($_SESSION["cart_array"]);
}
?>
<?php
// Adjust The Item Quantity
if (isset($_POST['itemToAdjust']) && $_POST['itemToAdjust'] != "") {
	$itemToAdjust = $_POST['itemToAdjust'];
	$itemQuantity = $_POST['itemQuantity'];
	$itemQuantity = preg_replace('#[^0-9]#i', '', $itemQuantity);
	if ($itemQuantity >= 100) {
		$itemQuantity = 99;
	}

	if ($itemQuantity < 1) {
		$itemQuantity = 1;
	}
	$i = 0;
	foreach ($_SESSION["cart_array"] as $each_item) {
		$i++;
		while (list($key, $value) = each($each_item)) {
			if ($key == "item_id" && $value == $itemToAdjust) {
				array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $itemToAdjust, "quantity" => $itemQuantity)));
			}
		}
	}
}

?>
<?php
// Remove Item If User Choose To
if (isset($_POST['idToRemove']) && $_POST['idToRemove'] != "") {
	$keyToRemove = $_POST['idToRemove'];
	if (count($_SESSION["cart_array"]) <= 1) {
		unset($_SESSION["cart_array"]);
	} else {
		unset($_SESSION["cart_array"]["$keyToRemove"]);
		sort($_SESSION["cart_array"]);
	}
}
?>
<?php
// Render The Cart For The User To View
if (!isset($_SESSION['product_name'])) {
    $_SESSION['product_name'] = array();
}
if (!isset($_SESSION['price'])) {
    $_SESSION['price'] = array();
}
include 'moneyFormat.php';
$cartOutput = "";
$cartTotal = "";
$cartTotalPrice = "";
$cartTotalPriceString = "";

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) {
		$item_id = $each_item['item_id'];
		$sql = "SELECT *
					FROM products
						WHERE id='".$item_id."'
					LIMIT 1";
		$res = mysqli_query($con, $sql);

		while ($row = mysqli_fetch_array($res)) {
			$productName = $row['product_name'];
			//$_SESSION["product_name"] = $productName;
			$price = $row['price'];
			$details = $row['details'];
		}

		$priceTotal = $price * $each_item['quantity'];
		$cartTotal += $priceTotal;

		//echo $_SESSION["product_name"] . "<br />";
		for ($i=0; $i < count($_SESSION["product_name"]); $i++) { 
			echo $_SESSION["product_name"]."<br />";
		}
		/*if (count($_SESSION["product_name"]) > 0) {
			echo $_SESSION["product_name"] . "<br />";
		}*/

		//setlocale(LC_MONETARY, "en_IN");
		$priceTotal = money_format("%10.2n", $priceTotal);
		$price = money_format("%10.2n", $price);

		$cartOutput .= '<tr>';
		$cartOutput .= '<td><a href="product.php?id='.$item_id.'">'.$productName.'</a><br />
						<img src="inventory_images/'.$item_id.'.jpg" alt='.$productName.' width="82" height="70" border="1">
						</td>';
		$cartOutput .= '<td>'.$details.'</td>';
		$cartOutput .= '<td style="text-align: center;"> '.$price.'</td>';
		$cartOutput .= '<td style="text-align: center;">
							<form action="cart.php" method="POST">
							<input type="text" name="itemQuantity" size="1" maxlenght="2" value="'.$each_item['quantity'].'"/>
							<input type="submit" name="btnAdjustQuantity'.$item_id.'" value="Change" />
							<input type="hidden" name="itemToAdjust" value="'.$item_id.'" />
							</form>
						</td>';
		//$cartOutput .= '<td style="text-align: center;">'.$each_item['quantity'].'</td>';
		$cartOutput .= '<td style="text-align: center;"> '.$priceTotal.'</td>';
		$cartOutput .= '<td style="text-align: center;">
							<form action="cart.php" method="POST">
							<input type="submit" name="btnDeleteQuantity'.$item_id.'" value="Remove" />
							<input type="hidden" name="idToRemove" value="'.$i.'" />
							</form>
						</td>';
		$cartOutput .= '</tr>';
		$i++;
	}
	$cartTotalPrice = money_format("%10.2n", $cartTotal);
	$cartTotalPriceString = "<div align='right' style='font-size: 19px; margin-removed 15px;'>Cart Total: ". $cartTotalPrice . "</div>";

}
?>
<?php
$totalItems = 0;
$checkOut = "";
$quantity = 0;

if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
	$cartOutput = "<h2 align='center'>Your Shopping Cart Is Empty.</h2>";
} else {
	foreach ($_SESSION["cart_array"] as $each_item) {
		while (list($key, $value) = each($each_item)) {
			if ($key == 'quantity' && $each_item['quantity'] > 0) {
				$totalItems += $value;
				$quantity = $totalItems;
			}
		}
	}
}

if ($totalItems > 0) {
	$checkOut = '<a href="storescripts/render_cart.php?checkout=YES&Product='.$productName.'&Quantity='.$quantity.'&Price='.$cartTotalPrice.'">';
	$checkOut .= '<input type="submit" value="Check Out" name="checkOut" style="float: right;"/>';
	$checkOut .= '</a>';
}
?>
Posted

I would simplify your handling of the arrays stored in the session.

You can add items to your cart more easily:
PHP
$_SESSION['test'][] = array(3, 6);
$_SESSION['test'][] = array(2, 4);

print_r($_SESSION['test']);


output:
Array ( 
  [0] => Array ( [0] => 3 [1] => 6 ) 
  [1] => Array ( [0] => 2 [1] => 4 ) 
)


You typically go through your array with foreach, so there's no need to worry about specific indices if you remove items from the middle of the cart. Note that I didn't assign the index to an element specifically. Specifically assigning an item risks overwriting it.
. . . 0 => array("item_id" => $id, "quantity" => 1) . . . 


Simplify handling your cart array and you should be able to work it out.
 
Share this answer
 
I made a shopping cart a while back. Here is the code. Posting it here maybe you could get an idea on how to do your cart (this is a very simple example and only for test... needs a whole lot more work to get it done to production level). This is just to give you an idea of what I've done and maybe on how you could fix your problem. Of course you'd want to validate user input before running them through the class.
PHP
class shoppingCart
{
    
    var $product = array();
    
    /*
     * public function add( int $pid, $int $qt )
     *      @integer $pid - The product ID
     *      @integer $qt - Quantity of our product
     * 
     *  Adds a product to the cart
    **/
    
    public function add($pid, $qt)
    {
        // To check if the item is already in cart
        // FALSE means it is not in cart yet (default)
        $in_cart = false;
        
        // Checking if we have a quantity set (can't have 0 amount of an item)
        if($qt < 1)
        {
            throw new exception("You're not adding any amount of the item.");
        }
        
        // Checking if we have a cart
        if(isset($_SESSION['shopping_cart']))
        {
            // Retrieving the contents of our cart (so we can add an item to it)
            $items = $this->showSaved();
            
            // Iterating through our carts and rebuilding it
            // Doing it this way in case they buy the same item again
            // in which case we just add quantity to the product id
            foreach($items as $p_id => $quantity)
            {
                // Checking if the item already exists in the cart
                if($pid == $p_id)
                {
                    // It exists... add quantity
                    $quantity = $qt + $quantity;
                    
                    // Make sure we tell the rest of the script that it is in cart
                    $in_cart = true;
                }
                
                // Product ID (key) and it's quantity (value)
                $product[$p_id] = $quantity;
            }
        }
        
        // Checking if it wasn't in cart... in which case we add it to cart
        if($in_cart == false)
        {
            // It wasn't in cart. Add it to cart.
            // Product ID (key) and it's quantity (value)
            $product[$pid] = $qt;
        }
        
        // Setting the product array
        $this->product = $product;
        
        // Saving the cart
        $this->save();
    }
    
    /*
     * public function remove( int $pid [, $int $qt ])
     *      @integer $pid - The product ID
     *      @integer $qt - Quantity of product to be removed
     * 
     *  Removes an item from the cart or a certain quantity of that item
     *  (if $qt is not 0)
    **/
    
    public function remove($pid, $qt = 0)
    {
        // Checking if we have a cart
        if(isset($_SESSION['shopping_cart']))
        {
            // Checking if the item requested to be removed is actually in the cart
            if(isset($_SESSION['shopping_cart'][$pid]))
            {
                // It is set... checking if we have a quantity set
                // (to subtract in case we aren't removing entirely)
                if($qt !== 0)
                {
                    // We are not removing the entire item but a certain quantity of it
                    // Checking if we have this (or more) of the product (so we don't
                    // come by a negative amount of a product
                    if($qt >= $_SESSION['shopping_cart'][$pid])
                    {
                        // We don't have that much of the item to remove
                        throw new exception("Trying to remove {$qt} of a product when you only have {$_SESSION['shopping_cart'][$pid]} of it!");
                        
                        // Returning false
                        return false;
                    }
                    
                    // Subtracting the quantity of the product
                    $_SESSION['shopping_cart'][$pid] = $_SESSION['shopping_cart'][$pid] - $qt;
                    
                    // Success... return true
                    return true;
                }
                else
                {
                    // We are to completely remove the product from the cart
                    unset($_SESSION['shopping_cart'][$pid]);
                    
                    // Success... return true
                    return true;
                }
            }
            else
            {
                // The item is not even in the cart... can't remove nothing!!!
                throw new exception("Item doesn't exist in the cart. Nothing to remove.");
            }
        }
        else
        {
            // The shopping cart doesn't exist yet. (Empty cart)
            throw new exception("The cart is empty. Nothing to remove.");
        }
    }
    
    function showSaved()
    {
        // Returning the shopping cart as an array
        return (array) $_SESSION['shopping_cart'];
    }
    
    function save()
    {
        // Saving the cart to the session
        $_SESSION['shopping_cart'] = $this->product;
    }
    
    function clearCart()
    {
        // Resetting the shopping cart session to an empty array
        $_SESSION['shopping_cart'] = array();
    }
}

session_start();
$cart = new shoppingCart();
?>

HTML
<p>The Shopping Cart:</p>
<p>To <strong>add</strong> to cart, simply select the product you want to add and type in the quantity and click 'Add'.</p>
<p>To <strong>clear</strong> the cart, simply click 'Clear Cart'.</p>
<p>To <strong>remove</strong> from cart, simply select the product and type in the quantity to remove (or leave blank to remove the item entirely) and click 'Remove from Cart'.</p>
<form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<p>Product: <select name="prods">
<option value="1">Pair or Socks</option>
<option value="2">Pair of Underwear</option>
<option value="3">The House on the Hill</option>
<option value="4">Laundry detergent</option>
<option value="5">Juice Boxes</option>
<option value="6">PHP Dev's Book</option>
</select><br />
Quantity: <input type="text" name="qt" size="10" /><br />
<input type="submit" name="submit" value="Add" /> 
<input type="submit" name="clear" value="Clear Cart" /> 
<input type="submit" name="remove" value="Remove from Cart" /><p></form>
<pre>
<pre>

PHP
// Trying to accomplish... so we can catch our errors here and handle them
try
{
    // Adding to cart
    if(isset($_POST['submit']))
    {
        // Adding to cart
        $cart->add($_POST['prods'], $_POST['qt']);
        
        // Displaying to cart
        print_r($cart->showSaved());
    }

    // Completely clearing entire cart
    if(isset($_POST['clear']))
    {
        // Clearing the cart
        $cart->clearCart();
        
        // Displaying the cart
        print_r($cart->showSaved());
    }

    // ( Decreasing amount of / removing ) the item
    if(isset($_POST['remove']))
    {
        // Making sure that we have a legitimate quantity to remove (0 to remove entirely)
        $qt = (integer) (isset($_POST['qt']) && !empty($_POST['qt'])) ? $_POST['qt'] : 0;
        
        // Removing from the cart
        $cart->remove($_POST['prods'], $qt);
        
        // Displaying the cart array
        print_r($cart->showSaved());
    }
}
catch( exception $e )
{
    echo "<pre>";>
    echo $e->getMessage() . ' In ' . $e->getFile() . ':' . $e->getLine() . '<br /><br />';
    echo "Stack Trace<br />";
    echo $e->getTraceAsString();
    echo "</pre>";
}
?>
 
Share this answer
 
v4
Comments
MaddyDesigner 16-Feb-14 1:11am    
Thanks dude. You saved my day !!!!
EZW 16-Feb-14 1:58am    
Glad to help! :)

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