Guest User

Guest User

  • Tech Writer
  • 2.1k
  • 472.4k

cart is empty but basket has items

Apr 25 2023 5:04 AM

Hi Team

I need some help with my shopping cart, i am adding item on the basket, but when i click on the basket for those item added its empty. 

            <div id="basket-overview" class="navbar-collapse collapse d-none d-lg-block">
  <a "basket.php" class="btn btn-primary navbar-btn">
    <i class="fa fa-shopping-cart"></i>
    <span id="cart-count"><?php echo count($_SESSION['cart']); ?></span>
  </a>
</div>

// basket.php
<?php
// Start the session
session_start();

echo count($_SESSION['cart']);
// Check if the cart is not empty
if (!empty($_SESSION['cart'])) {
    // Establish database connection.
    $conn = mysqli_connect('localhost', 'root', '', 'ecommerce_store');
    if (!$conn) {
        die('Could not connect to database: ' . mysqli_connect_error());
    }

    // Query the database to get the products in the cart
    $cart_items = array();
    foreach ($_SESSION['cart'] as $product_id => $quantity) {
        $sql = "SELECT * FROM products WHERE productID = '$product_id'";
        $result = mysqli_query($conn, $sql);
        if (!$result) {
            die('Error getting product details: ' . mysqli_error($conn));
        }
        $product = mysqli_fetch_assoc($result);
        $product['quantity'] = $quantity;
        $cart_items[] = $product;
    }

    // Close the database connection
    mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart</title>
    <
</head>
<body>
<div class="container">
    <h1>Shopping Cart</h1>
    <?php if (!empty($cart_items)): ?>
        <table class="table">
            <thead>
                <tr>
                    <th>Image</th>
                    <th>Product Name</th>
                    <th>Unit Price</th>
                    <th>Quantity</th>
                    <th>Discount</th>
                    <th>Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($cart_items as $cart_item): ?>
                <tr>
                    <td><img src="<?php echo $cart_item['image']; ?>" alt="<?php echo $cart_item['product_name']; ?>"></td>
                    <td><?php echo $cart_item['product_name']; ?></td>
                    <td>$<?php echo $cart_item['unit_price']; ?></td>
                    <td><?php echo $cart_item['quantity']; ?></td>
                    <td><?php echo $cart_item['discount']; ?></td>
                    <td>$<?php echo ($cart_item['unit_price'] * $cart_item['quantity'] * (1 - $cart_item['discount'])); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>Your cart is empty.</p>
    <?php endif; ?>
</div>
</body>
</html>


// get_product_details.php
<?php

session_start();
/*
*@author:Gcobani Mkontwana
*@date:21/04/2023
*Get the product details.
**/

// Establish database connection.
$conn = mysqli_connect('localhost', 'root', '', 'ecommerce_store');
if (!$conn) {
    die('Could not connect to database: ' . mysqli_connect_error());
}

// session for cart.
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

// Query the database to get the products in the cart
$cart_items = array();
foreach ($_SESSION['cart'] as $product_id => $quantity) {
    $sql = "SELECT * FROM products WHERE productID = '$product_id'";
    $result = mysqli_query($conn, $sql);
    if (!$result) {
        die('Error getting product details: ' . mysqli_error($conn));
    }
    $product = mysqli_fetch_assoc($result);
    $product['quantity'] = $quantity;
    $cart_items[] = $product;
}

// Close the database connection
mysqli_close($conn);
?>
<!-- Display the cart items in a table -->
<!DOCTYPE html>
<html>
<head>
    <title>Shopping Cart</title>
    rel="stylesheet">
</head>
<body>
<table class="table">
    <thead>
        <tr>
            
            <th>Product Name</th>
            <th>Product ID</th>
            <th>Unit Price</th>
            <th>Quantity</th>
            <th>Discount</th>
            <th>Amount</th>
            
        </tr>
    </thead>
    <tbody>
        <?php foreach ($cart_items as $product_id => $cart_item): ?>
        <tr>
            
            <td><?php echo $cart_item['product_name']; ?></td>
            <td><?php echo $product_id; ?></td>
            <td>$<?php echo $cart_item['unit_price']; ?></td>
            <td><?php echo $cart_item['quantity']; ?></td>
            <td><?php echo $cart_item['discount']; ?></td>
            <td>$<?php echo ($cart_item['unit_price'] * $cart_item['quantity'] * (1 - $cart_item['discount'])); ?></td>
            <td>
                <form method="POST" action="remove_from_cart.php">
                    <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                    <button type="submit" class="btn btn-link text-danger">Remove</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
</body>
</html>


// jquery code
function addToCart(productId, quantity) {
  var cart = getCart();
  if (cart.hasOwnProperty(productId)) {
    var newQuantity = parseInt(quantity);
    if (newQuantity <= 0) {
      delete cart[productId];
    } else {
      cart[productId] = newQuantity;
    }
  } else {
    cart[productId] = parseInt(quantity);
  }
  saveCart(cart);
  updateCartCount();
  calculate_total();

  // Display message
  var productName = $('#product-name-' + productId).text();
  $('#cart-message').text(quantity + 'x ' + productName + ' added to cart').show();
  
  setTimeout(function() {
    $('#cart-message').fadeOut('slow');
  }, 3000);
}

function calculate_total() {
  var cart = getCart();
  var total = 0;
  for (var productId in cart) {
    var product = getProductId(productId);
    var price = parseFloat(product.price);
    var quantity = parseInt(cart[productId]);

    // Send request to server to get discount for the product
    $.ajax({
      url: 'get_product_details.php',
      data: {productId: productId},
      dataType: 'json',
      success: function(data) {
        // Update HTML elements with discount and amount
        var discount = parseFloat(data.discount);
        var amount = price * quantity * (1 - discount);
        $('#discount-' + productId).text((discount * 100).toFixed(0) + '%');
        $('#amount-' + productId).text('$' + amount.toFixed(0));
      },
      error: function(xhr, textStatus, errorThrown) {
        console.log('Error getting product details: ' + errorThrown);
      }
    });

 


Answers (2)