Jump to content

Problem Solved - How $_SESSION['cart'] is being set - OOP Shopping Cart video - Video 25 and 22


Recommended Posts

Posted (edited)

So here seems to be the stages leading up to $_SESSION['cart'] being set:

First, someone clicks a link generated by m_products 'cart.php? id=' . $product['id'] 

Second, cart.php sees the product id in the url (generated by someone clicking the above link), and calls this function in m_cart.php to add a product: $Cart->add($_GET['id']);

Third, m_cart.php starts this function: 

public function add($id, $num = 1)
    public function add($id, $num = 1)
    {
        //setup or retrieve cart
        $cart = array();
        if(isset($_SESSION['cart']))
        {
            $cart = $_SESSION['cart'];
        }
        //check to see if item is already in cart
        if (isset($cart[$id]))
        {
            //if item is in cart
            $cart[$id] = $cart[$id] + $num;
        }
        else
        {
            // if item is not in cart
            $cart[$id] = $num;
        }
        $_SESSION['cart'] = $cart;
    }

The section of code above that I have highlighted is where $_SESSION['cart'] is initially set.  I was having trouble before, because I hadn't cleared the cart before running the public function add.  As a result, every time I tested this line of code, I did so assuming the $_SESSION['cart'] was empty.  But when I tested the code the first conditional kept resolving to true, as if the cart had already been set (even though I thought it hadn't been).

At any rate, here is how $_SESSION['cart'] is set.  The first two conditionals in public function add resolve to false: $_SESSION['cart'] has not been set yet (provided no previous items were added to the cart).  And, if $_SESSION['cart'] hasn't been set yet, there won't be a key of $id in the variable $cart -  as $cart is just a blank array.  So, that means the last piece of code will fire: a previously blank array ($cart) will be given a key ([$id]) and a value of $num (which is just 1).  Then, the information in variable $cart is assigned (given) to $_SESSION['cart'].

Edited by Drew2
  • Like 1
  • Drew2 changed the title to Problem Solved - How $_SESSION['cart'] is being set - OOP Shopping Cart video - Video 25 and 22

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...