Passing values to a Cart

I am kinder new in PHP but I mastered a lot. However, I have one issue with passing a value from a database to a Cart. I’ll have some codes below. I’ll just attach sections of the codes that give me trouble. Hopefully, I get some help.

This is a sample of my carts index page

if (empty($_SESSION['cartg'])) {
    $cart = array ();
} else {
    $cart = $_SESSION['cartg'];
}

// Include cart functions

require_once('../model/cart.php');
require('../model/glass_color.php');
require('../model/glass_color_db.php');
require('../model/glass.php');
require('../model/glass_db.php');
require('../model/g_database.php');
$glasscolorDB = new GlassColorDB();
$glassDB = new GlassDB();
$glass = new Glass();

$color_id = filter_input(INPUT_GET, 'glass_color_id', FILTER_VALIDATE_INT);
        
        if ($color_id == NULL || $color_id == FALSE){
            $color_id = 1;
        }
        
        $current_color = $glasscolorDB->getGlassColor($color_id);
        
        $colors = $glasscolorDB->getGlassColors();

// $glasses returns an array from the GlassDB class 

        $glasses = $glassDB->getGlassesByGlassColor($color_id);

  // Get the action to perform
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
    $action = filter_input(INPUT_GET, 'action');
    if ($action === NULL) {
        $action = 'show_add_glass';
    }
}

// Add or update cart as needed
switch ($action) {
    case 'add':
        $key = filter_input(INPUT_POST, 'productkey');
        $quantity = filter_input(INPUT_POST, 'glassqty');
        ndikum\cart\add_glass($cart, $key, $cost, $quantity);
        $_SESSION['cartg'] = $cart;
        include('cart_view.php');
        break;
    case 'update':
        $new_qty_list = filter_input(INPUT_POST, 'newqty', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        foreach($new_qty_list as $key => $qty) {
            if ($cart[$key]['qty'] != $qty) {
                ndikum\cart\update_item($cart, $key, $qty);
            }
        }
        $_SESSION['cartg'] = $cart;
        include('cart_view.php');
        break;
    case 'show_cart':
        include('cart_view.php');
        break;
    case 'show_add_glass':
        
        include('add_glass_view.php');
        break;

Codes from my add_glass_view page 

// This section collects items from the $glassess array as needed by the user

                <label>Name: </label>
                <select name="productkey" >
                    <?php foreach($glasses as $key => $glass) :
                    $id = $glass->getID();
                    $cost = number_format($glass->getPrice(), 2);
                    $name = $glass->getName();
                    $item = $name . ' ($' . $cost . ')';
                    ?>
                    <option value="<?php echo $key; ?>">
                        <?php echo $item; ?>
                    </option>
                    <?php endforeach; ?>

// Codes from the cart.php model page

namespace ndikum\cart {
        
        // Add a glass type to the cart
        function add_glass (&$cart, $key, $cost, $quantity) {
            global $glasses;
            if ($quantity < 1) return;
            
            // If a glass type already exists in cart, update quantity
            if (isset($cart[$key])) {
                $quantity += $cart[$key]['qty'];
                update_item($cart, $key, $quantity);
                return;
            }
            
            // Add glass
           // $cost = $glasses[$key]['listPrice'];
            $total = $cost * $quantity;
            $glass = array (
                'glass_id' => $glasses[$key]['glass_id'],
                'glass_name' => $glasses[$key]["glass_name"],
                'listPrice' => $cost,
                'qty' => $quantity,
                'total' => $total
            );
            $cart[$key] = $glass;
        }

// Code that needs to submit to cart the value and this where I have issues

        <form action="." method="post">
                <input type="hidden" name="action" value="update">
                <table>
                    <tr id="cart_header">
                        <th class="left">Glass</th>
                        <th class="right">Glass Cost</th>
                        <th class="right">Quantity</th>
                        <th class="right">Glass Total</th>
                    </tr>
                <?php foreach($cart as $key => $item) :
                         $cost = number_format($item['listPrice'], 2);  **// The application keep telling me there is an undefined index 'listPrice'. How do I fix this so the index is read to the array**
                    $total = number_format($item['total'], 2); ?>
                    <tr>
                        <td>
                            <?php echo $item['glass_name']; ?>
                        </td>
                        <td class="right">
                            $<?php echo $cost; ?>
                        </td>
                        <td class="right">
                            <input type="text" class="cart_qty" name="newqty[<?php echo $key; ?>]" value="<?php echo $item['qty']; ?>">
                        </td>
                        <td class="right"> $<?php echo $total; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>

You have far too much code and variables, to even begin to tell what or where the problem is. Keep It Simple (KISS.)

Your session cart definition should use the item id as the array index and the quantity as the array value under the index.This is the only data that should be stored in the cart. All other data should be gotten from the database when needed.

Also, every variable, function, method,… that contains the word ‘glass’ is mis-named. These are items that are being displayed and added to the cart. It doesn’t matter what they actually are. Your code and any naming should be general-purpose.

1 Like

Thanks much. I made my session cart definition to use the item id from the database as the array index and that index problem stop coming up. However, I have another problem. I’ll disclose the different files and the code to see if I can be helped.

If I have a file “add_glass_view” that display the Item view with code that collect items from the database as so

<label>Name: </label>
                <select name="productkey" >
                    <?php foreach($glasses as $key => $glass) :
                    $id = $glass->getID();
                    $cost = number_format($glass->getPrice(), 2);
                    $name = $glass->getName();
                    $item = $name . ' ($' . $cost . ')';
                    ?>
                    <option value="<?php echo $key; ?>">
                        <?php echo $item; ?>
                    </option>
                    <?php endforeach; ?>
                </select><br> 

I guess the value is stored in a key as an array. Let’s say the key is collected by the “index page” as so

switch ($action) {
    case 'add':
        $key = filter_input(INPUT_POST, 'productkey');
        $quantity = filter_input(INPUT_POST, 'glassqty');
        ndikum\cart\add_glass($cart, $key, $quantity);
        $_SESSION['cartg'] = $cart;
        include('cart_view.php');
        break;

I want to assume the key value is now collected and pass to the add_glass() function. How do I collect these key values in a file called “cart.php” so I can process it to the cart? The code I currently have in “cart.php” is

 namespace ndikum\cart {
        
        // Add a glass type to the cart
        function add_glass (&$cart, $key, $quantity) {
            global $glasses;
            if ($quantity < 1) return;
            
            // If a glass type already exists in cart, update quantity
            if (isset($cart[$key])) {
                $quantity += $cart[$key]['qty'];
                update_item($cart, $key, $quantity);
                return;
            }
            
            // Add glass
            $cost = $glasses[$key]['listPrice'];
            $total = $cost * $quantity;
            $glass = array (
                'glass_id' => $glasses[$key]['glass_id'],
                'glass_name' => $glasses[$key]["glass_name"],
                'listPrice' => $cost,
                'qty' => $quantity,
                'total' => $total
            );
            $cart[$key] = $glass;
        }

Using the suggestion of only storing the quantity in the cart, the following is the simplest logic needed to perform this operation -

// insert an item if it doesn't exist
if(!isset($cart[$key]))
{
	$cart[$key] = 0; // create with a zero quantity. the submitted quantity will be added in the next step.
}

// add the submitted quantity to the existing quantity (which could be zero if the item was just inserted above.)
$cart[$key] += $quantity;
Sponsor our Newsletter | Privacy Policy | Terms of Service