Jump to content

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


Drew2

Recommended Posts

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
Link to comment
Share on other sites

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...