Project structure is as follows:
A home page (store_home1.php) which lists various products and links user to a products page using GET method .

A products page (product.php) which shows the user more detail and links them to the shopping
cart page via ADD TO CART submit button using POST method.

Shopping cart page (cart.php) which uses a $variable to echo a table that displays products added to cart.

I am working with a shopping cart script and having trouble [COLOR="#FF0000"]increasing quantity[/COLOR] in the cart.

If the user selects a product and clicks ADD TO CART , that product is added to the cart and the qty shows 1. It does not matter which product the user chooses to add to the cart.

If the user uses the  browser back button to return to the product page or home page and attempts to add the product again the cart page shows the following:

Notice: Undefined index: quantity inC:\xampp\htdocs\tutorials\kensStore\cart.phpon line*70

Notice: Undefined index: quantity inC:\xampp\htdocs\tutorials\kensStore\cart.phpon line*76
and the qty in the cart display changes from 1 to 0.

Is there a problem with a problem with the array_splice on line 29 that changes “quantity” key  value to $each_item['quantity'] ?

Line 29:

array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> [COLOR="#FF0000"]$each_item['quantity'][/COLOR]+1)));

Or is there some kind of session persistence problem because the user has to use browser back button?

Either way, I don't know how to correct this.

The problem referenced lines 70 & 76 are in section 3 of this code.
70: $priceTotal = $price * $each_item['quantity'];
76:$cartOutput .= "<td>" .$each_item['quantity']. "</td>";

If you require additional info let me know.
Or require code for the other pages.

<?php 
session_start();
?>
<?php 
include "conn_to_mysqli.php";
?>

<?php
///////////////////////////////////////////////////////////////////////////////
//Section 1 (check for items in cart, adjust quantities , or add items to cart)
///////////////////////////////////////////////////////////////////////////////
if (isset($_POST ['pid'])) {
	$pid = $_POST ['pid'];
	$wasFound = false;
	$i = 0; //this represents the index of the array
	//check the cart session variable is not set or the cart array is empty
	if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
		//run if the cart is not set or empty
		$_SESSION["cart_array"] = array (1=> array("item_id"=> $pid, "quantity" => 1));
	}  else {
		// run if the cart has at least one item
		foreach ($_SESSION["cart_array"] as $each_item) {
			$i++; //holds a numeric representation of which associative array of our multidemensional array is passing through the loop
			while(list($key,$value)=each($each_item)){
			if ($key== "item_id" && $value == $pid) {
				//the above if statement is how you find the match to the item already in cart
				//that item is already in the cart so adjust quantity using array_splice
				//array splice removes a portion of an array and replaces it with something else
				array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quaniity"=> $each_item['quantity']+1)));
				$wasFound = true;
			}//close if condition
		}//close while loop
	}// close foreach loop
	if($wasFound==false) {
		//so if this item isn't already in the cart it puts it in the cart
		//array_push puts new associative array into your multi dimensional array. Remember pic ?
		array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));		
		}
	}
}
?>

<?php 
////////////////////////////////////////////////////////////////
//Section 2 (if the user chooses to empty their shopping cart )
///////////////////////////////////////////////////////////////
if(isset($_GET['cmd']) && $_GET['cmd']=="emptycart") {
	unset($_SESSION["cart_array"]);
}
?>

<?php 
///////////////////////////////////////////////////
//Section 3 (render the cart for the user to view)
//////////////////////////////////////////////////
$cartOutput ="";
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++;
			$item_id = $each_item['item_id'];			
			$sql = mysqli_query($con, "SELECT * FROM products WHERE id = '{$item_id}'LIMIT 1");    
while ($row = mysqli_fetch_array($sql)) { $product_name = $row['product_name']; $price = $row['price'];
$details = $row['details']; } $priceTotal = $price * $each_item['quantity']; //dynamic table row assembly $cartOutput .= "<tr>"; $cartOutput .= "<td>" .$product_name. "<br/><img src=\"store_admin/inventory_images/$item_id.jpg\" alt=\"product_name\" width=\"48\" height=\"48\"/></td>"; $cartOutput .= "<td>" .$details. "</td>"; $cartOutput .= "<td>" .$price. "</td>"; $cartOutput .= "<td>" .$each_item['quantity']. "</td>"; $cartOutput .= "<td>" .$priceTotal. "</td>"; $cartOutput .= "<td> X </td>"; $cartOutput .= "</tr>"; echo $priceTotal; echo var_dump($priceTotal); } } ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Your Cart</title>
<link rel="stylesheet" type="text/css" href="product.css" >
</head>

<body>
	<div id="pagewrap" > 
		<div id="pageHeader"><h1>Sunrise Side Sporting Goods<h1>

	<p align="center"><a href="cart.php"> <img src="style/shop-cart-check.png" width="64" height="64" /> Your Cart</a></p>
	<nav id="top_nav">
		<ul> 
			<li><a class="topLinks" href="store_home1.php">Home</a></li>
			<li><a class="topLinks" href="">link2</a></li>
			<li><a class="topLinks" href="">link3</a></li>
			<li><a class="topLinks" href="">link4</a></li>
			<li><a class="topLinks" href="">link5</a></li>
			<li><a class="topLinks" href="">link6</a></li>
		</ul>
	</nav>
	</div>


<section id="middle">
	<h2><center>Welcome to Your Cart</center></h2>


	<table width="100%" border="1" cellpadding="3">
		<tr id="row1" name="row1">
			<td width="20%" style="background: blue; color: white;"> Product</td>
			<td width="40%" style="background: black; color: #00FF00;"> Product Details</td>
			<td width="10%" style="background: black; color: #00FF00;"> unit price</td>
			<td width="10%" style="background: black; color: #00FF00;"> Qty</td>
			<td width="10%" style="background: black; color: #00FF00;"> $ Total</td>
			<td width="10%" style="background: black; color: #00FF00;"> Remove</td>
		</tr>
		<?php echo $cartOutput; ?>
	</table>
	<br><br>
	<p><a href="cart.php?cmd=emptycart"> <img src="style/Shop-cart-exclude.ico" width="64" height="64" /> Click Here to Empty Your Cart</a></p>
	<p align="right"> <a href="store_home1.php" target="_blank"> Continue Shopping</a></p>
</section>

<aside id="sidebar">
	<h2>3rd Content Area</h2>
	<p>This is some text in a paragraph</p>
	<p>This is some more text in annother paragraph</p>
	<p>This is even more text in yet annother paragraph </p>
</aside>

<footer>
	<h4>Footer</h4>
	<p>Footer text</p>
</footer>
</div>
</body>
</html>








	<div id="pageFooter"> Footer </div>
</div>
</body>

</html>

    You have a typographical error on this line:

    array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quaniity"=> $each_item['quantity']+1)));

    "quaniity" should have been "quantity"

      Awesome laserlight. Always good to have fresh pair of eyes on things.
      I must have looked at that line of code at laest 12 times and didn't see that.
      Thank you.
      Still have one persisting problem. $priceTotal = $price * $each_item['quantity'];
      Is not changing the total in the display.
      Can you help?

        [ATTACH]5447[/ATTACH]
        here is screen shot

        Your Cart.png

          The reason your total isn't working is because your price data contains the $ character and when you treat it as a number, in the calculation, it's treated as a zero, since a $ isn't a valid decimal digit. Your price should only be the value. When you display the price, is where you should output the currency symbol.

          Next, if you simplify your cart definition, the add to cart and display cart code will be greatly simplified. Use the product id/pid as the array index and the quantity as the value. This will allow you to directly test if an item is already in the cart, to insert it if it is not, and to add one to the quantity if it is.

          Using this definition, the following is all the code you need for the add to cart -

          if (isset($_POST ['pid']))
          {
          	$pid = (int)$_POST['pid']; // at a minimum, cast this as to correct data type
          	if(!isset($_SESSION["cart_array"][$pid]))
          	{
          		// not in the cart, insert it with a quantity zero (the next line of code will set it to a one)
          		$_SESSION["cart_array"][$pid] = 0;
          	}
          	// add one to the quantity
          	$_SESSION["cart_array"][$pid]++;
          }

          For the display cart code, you should NOT run an sql query inside of a loop and you shouldn't loop to retrieve data from a query that will at most match a single row of data. Using the suggested cart definition, you can get all the product id values using array_keys(). You would then use the product id values in a single sql query statement to get all the product information at once. You would loop over the product information to display it, and use the id to get the quantity from the cart.

            pbismad.
            Thank you for pointing out the mistake concerning the "$" symbol.
            I edited the items already in the database, removing the currency symbol resolved my problem.
            In the inventory upload page I also changed the form input element for price from text to number so that this can be avoided in the future. I suppose I could have used a preg_replace, but changing input type
            seems better.
            I am satisfied with the functionality as is. I may revisit your suggested method at a later date.
            Again. Thank you.

            I will mark as resolved.

              New_PHP_Guy;11061313 wrote:

              Awesome laserlight. Always good to have fresh pair of eyes on things.
              I must have looked at that line of code at laest 12 times and didn't see that.
              Thank you.
              Still have one persisting assurance chien problem. $priceTotal = $price * $each_item['quantity'];
              Is not changing the total in the display.
              Can you help?

              Hello!
              I'a new member here and i'm completly lost and i don't know what to do!
              Thanks!

                Write a Reply...