Search code examples
phpsessionwhile-loopshopping-cartarray-push

session based shopping cart


Originally I got it to work fine, in passing the product id over, through the array_push() function, going from addtocart.php to Shoppingcart.php displaying the items. But when I add more variables/into the array_push() function, other that the single product id $_GET['id'], ... on the next page that receives this array, it gives me an error.

The problem is: In the original $sql query it was getting the id it needs to display the products info from the array_push() and display it on to Shoppingcart.php, but when I add more variables/info into the push_array() I get an error. Because its confuses the $sql query, because of the WHERE id IN clause … the ID is still in there, now along with the other info($_GET['size'] & $_GET['qty']), I just don’t know how to access it...

How can I add more info into the push array, but some how define it so I can grab the id for my $sql query, to get the product info, but also have access to the size & Qty for my while() loop.

addtocart.php

array_push($_SESSION['cart'], $_GET['id']); //working MAIN
header('Location:shoppingCart.php');

How 2: array_push($_SESSION['cart'], $_GET['id'], $_GET['size'],  $_GET['qty']); 
//Not Working

shoppingcart.php

    <?php 
    $whereIn = implode(',', $_SESSION['cart']); //working MAIN
    $sql = " SELECT * FROM inventory WHERE id IN ($whereIn) "; ?>

 <?php while($row = mysql_fetch_array($result)) { ?>

<td  valign="top">
    <div id="sc_itemBox">
        <p class="sc_itemBox_iTEXT"><strong>SIZE:</strong> “”XL?? <em>(Extra Large??)</em></p>
        <div id="sc_itemBox_img"><img src="<?php echo $row['imgThumb'];?>" /></div>
        <p class=<p class="sc_itemBox_iTEXT"><strong>STYLE#</strong><?php echo $row['styleNUM']; ?> </p>
    </div>        
</td>
<?php } ?>

Solution

  • I think making your $_SESSION['cart'] a little more complex may do the trick. Try to separate out your id and such into their own array(s). Maybe something like.

    addtocart.php

    if(isset($_SESSION['cart'])) {
            // Store just ids
            // Use array_unique to filter this array
            $_SESSION['cart']['id'] = array_unique($_SESSION['cart']['id']);
            // Save new cart array with that items basics
            $_SESSION['cart'][$_GET['id']]['size'][] = $_GET['size'];
            $_SESSION['cart'][$_GET['id']]['qty'][]  = $_GET['qty'];
            header('Location:shoppingCart.php');
            exit;
        }
    

    shoppingcart.php

    // Implode just the id array, no other array in the cart session
    // (make sure your addtocart checks for is_numeric so you don't get someone
    // injecting sql junk into your db
    $whereIn    =    implode(',', $_SESSION['cart']['id']);
    $sql        =    "SELECT * FROM inventory WHERE id IN ($whereIn)";
    

    EDIT: Here is a way to do it so that you break out your items into sizes (incase you are adding multiple items with the same id but at different sizes and quantities:

        function AddToCart()
            {
                // Confirm that an id is being added
                // I am assuming there is an "add" trigger
                if(isset($_GET['add']) && is_numeric($_GET['id'])) {
                        // Create the item in the cart
                        // Record size
                        if(isset($_SESSION['cart'][$_GET['id']]['size'][$_GET['size']]['qty']))
                            // Notice here that if there is already this item in the cart
                            // with the exact same size, it will sum
                            $_SESSION['cart'][$_GET['id']]['size'][$_GET['size']]['qty']    +=  $_GET['qty'];
                        else
                            // If not in cart at this size, it will add qty
                            $_SESSION['cart'][$_GET['id']]['size'][$_GET['size']]['qty']    =   $_GET['qty'];
                    }
            }
    
        // Fetch ids for your query 
        function FetchItems()
            {
                if(isset($_SESSION['cart'])) {
                        foreach($_SESSION['cart'] as $itemcode => $array) {
                                $items[]    =   $itemcode;
                            }
    
                        return (isset($items))? $items:false;
                    }
            }
    
        // Start the session
        session_start();
    
        // Add to cart
        AddToCart();
        // This will fetch your ids for your query
        $mysqlIds   =   implode(",",FetchItems());
    
        echo '<pre>';
        print_r($mysqlIds);
        echo '</pre>'; ?>
    
        <!-- These are just for testing. Will generate different sizes and qty-->
        <a href="?add=true&id=1&size=<?php echo rand(1,12); ?>&qty=<?php echo rand(0,5); ?>">ID 1</a>
        <a href="?add=true&id=2&size=<?php echo rand(1,12); ?>&qty=<?php echo rand(0,5); ?>">ID 2</a>
        <a href="?add=true&id=3&size=<?php echo rand(1,12); ?>&qty=<?php echo rand(0,5); ?>">ID 3</a>
    

    WILL GIVE YOU:

    // Session array after adding items to it.
    Array
    (
        [cart] => Array
            (
                [2] => Array
                    (
                        [size] => Array
                            (
                                [21] => Array
                                    (
                                        [qty] => 1
                                    )
    
                                [9] => Array
                                    (
                                        [qty] => 2
                                    )
    
                                [8] => Array
                                    (
                                        [qty] => 0
                                    )
    
                                [7] => Array
                                    (
                                        [qty] => 20
                                    )
    
                                [2] => Array
                                    (
                                        [qty] => 5
                                    )
    
                            )
    
                    )
    
                [3] => Array
                    (
                        [size] => Array
                            (
                                [9] => Array
                                    (
                                        [qty] => 3
                                    )
    
                                [1] => Array
                                    (
                                        [qty] => 0
                                    )
    
                                [7] => Array
                                    (
                                        [qty] => 4
                                    )
    
                                [10] => Array
                                    (
                                        [qty] => 6
                                    )
    
                                [3] => Array
                                    (
                                        [qty] => 20
                                    )
    
                                [2] => Array
                                    (
                                        [qty] => 10
                                    )
    
                                [12] => Array
                                    (
                                        [qty] => 2
                                    )
    
                                [6] => Array
                                    (
                                        [qty] => 10
                                    )
    
                            )
    
                    )
    
                [1] => Array
                    (
                        [size] => Array
                            (
                                [11] => Array
                                    (
                                        [qty] => 1
                                    )
    
                                [3] => Array
                                    (
                                        [qty] => 3
                                    )
    
                                [2] => Array
                                    (
                                        [qty] => 2
                                    )
    
                            )
    
                    )
    
            )
    
    )
    
    // This is for the ids for your mysql query
    2,3,1