Jump to content
Larry Ullman's Book Forums

Showing Items In Shopping Cart


Recommended Posts

I have created the shopping cart as in the book:

 

I am tring to show on each page how many items are in the cart. But, it only shows 1 item even if there are 5 items in the cart. The code I am using is:

<?php
  session_start();
  function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
 return '<p>You have no items in your shopping cart</p>';
} else {
  $items = explode(',', $cart);
 return '<p>You have <a href="basket.php"> '.count($items).' in your shopping cart</a></p>';
 }
}
echo writeShoppingCart();?>

 

I guess it is not bringing an array from the cart, but dont know how to show this in the above.

 

A snippet from my cart is:

session_start();
$_SESSION['cart'];
$page_title = 'Add to cart';
if (isset ($_GET['pid']) && is_numeric($_GET['pid']) ) {
$pid = (int) $_GET['pid'];
if (isset($_SESSION['cart'][$pid])) {
 $_SESSION['cart'][$pid]['quantity']++;
}else{ //new product
require_once ('../mysqli_connect.php');
$q="SELECT price, product_name FROM product WHERE product_id=$pid";
$r=mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) {
list($price, $product_name) = mysqli_fetch_array ($r, MYSQLI_NUM);
$_SESSION['cart'][$pid] = array ('quantity' => 1, 'price' => $price, 'product_name' => $product_name);
}else{
echo '<div align="center">Your basket has been updated</div>';
}
}
}else{
echo '<div align="center"> Your basket has been updated</div>';
}
if (isset($_POST['submitted'])) {
foreach ($_POST['qty'] as $k => $v) {

 $pid = (int) $k;
 $qty = (int) $v;

 if ($qty ==0) {
  unset ($_SESSION['cart'][$pid]);
 } elseif ($qty >0 ) {
  $_SESSION['cart'][$pid]['quantity'] = $qty;
 }
 }
}
if (!empty($_SESSION['cart'])) {
require_once ('../mysqli_connect.php');
$q="SELECT product_id, description, price, product_name FROM product WHERE product_id IN (";				 foreach ($_SESSION['cart'] as $pid => $value) {

Link to comment
Share on other sites

$_SESSION['cart'] is an array, not a string, so you can just return count($_SESSION['cart']). This doesn't take into account having multiple of the same item, however. To check for that, you'd need to loop through the array and add them up.

Link to comment
Share on other sites

  • 2 weeks later...

Hi Larry

 

I have tried this, but it does not matter how many items I put in my basket it only says that there is 1 item in my cart

 

  <?php
  session_start();
  function writeShoppingCart() {
  $items = 0;
foreach ($_SESSION['cart'] as $item) {
   $items += $item['quantity'];
}
 return '<p>You have <a href="basket.php"> '.count($items).' in your shopping cart</a></p>';
 }
echo writeShoppingCart();?>

Link to comment
Share on other sites

 Share

×
×
  • Create New...