Search code examples
phpe-commercesession-variablesshopping-cart

Display item list in shopping cart using PHP


With the foreach loop I'm trying to connect to my database and display in a list the products that have been added to the cart. Each product has a product ID which is correctly working and being stored in the session variable through the cart.php. I can't figure out how to connect to the database to display the information gathered about the product added - I also tried doing var_dump $SESSION['cart'] and its prints out null even after I use the "Add" button in cart.php.

<div class="row">
    <h4>Shopping Cart</h4>
            <?php

            foreach($_SESSION['cart'] as $proid => $proq) {

                // $proid is product id and $proq is quantity
                // use $proid to select the product detail from database

                }
            ?>
</div>
    <!--Below is my cart.php page-->
    <?php
    session_start();

    $productID = $_GET['product'];
    $action = $_GET['action'];

    switch($action) {

    case "add":
    $_SESSION['cart'][$productID]++;
    break;

    case "remove":
    $_SESSION['cart'][$productID]--;
    if($_SESSION['cart'][$productID] == 0) unset($_SESSION['cart'][$productID]);
    break;

    case "empty":
    unset($_SESSION['cart']);
    break;
    }
    header("Location: browse.php");


    ?>

Solution

  • Based on your explanation, you are trying to retrieve data from a session value to populate a database query.

    However, when your for loop executes, you have not de-serialized the session data into memory (so it cannot be accessed and you get null values).

    You need to start the session before your for loop:

    session_start();
    foreach($_SESSION['cart'] as $proid => $proq) {
    

    Please see more information in the php manual

    Also, you can configure PHP to start the session automatically if desired (see more details in the manual linked above), however keep in mind that this will have a performance impact even on pages which do not rely on session data.