Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating shopping cart object with SESSION
    primarykey
    data
    text
    <p>How should I create my shopping cart object without overwriting the session/object each time? My code below doesn't work properly because when I've added items each time I click the submit button it start from scratch and overwrites the basket.</p> <p>See live version here: <a href="http://www.animportantdate.co.uk/home/products.php" rel="nofollow">http://www.animportantdate.co.uk/home/products.php</a></p> <p>My code is:</p> <pre><code> session_start(); include('oopCart.php'); $basket = new shoppingCart($_SESSION['cart']); if (isset($_POST['submit'])){ $id = $_POST['id']; $qty = $_POST['qty']; $basket-&gt;addItem($id, $qty); } ?&gt; &lt;form method="POST" action="products.php"&gt; &lt;input type="hidden" value="dog" name="id"&gt; &lt;input type="hidden" value="10" name="qty"&gt; &lt;input type="submit" value="buy 10 dogs" name="submit"&gt; &lt;/form&gt; &lt;?php echo '&lt;BR&gt;items in basket: '. $basket-&gt;countItems(); echo '&lt;BR&gt;Total number of dogs (201): '. $basket-&gt;numberOfProduct('dog'); echo '&lt;BR&gt;is dog in basket? '. $basket-&gt;isInCart('dog'); ?&gt; </code></pre> <p>edit: i've added some of the shoppingcart class below. I should mention that when I create the object and test all the methods it contains in the same php file it works fine. Thus the methods all work well. It's just the instantiating that's causing me problems.</p> <pre><code> class ShoppingCart{ protected $id; protected $qty; protected $cart = array(); // constructor accepts the session variable to create cart object function __construct($cart=""){ $this-&gt;cart = $cart; } function addItem($id, $qty=1){ if (($this-&gt;isInCart($id)) == false ){ $this-&gt;cart[$id] = array( 'id' =&gt; $id, 'qty' =&gt; $qty); } else{ $this-&gt;cart[$id]['qty'] += $qty; } } function isInCart($id){ $inCart=false; if ($this-&gt;cart[$id]){ return $inCart=true; break; } return $inCart; } public function isEmpty(){ return (empty($this-&gt;cart)); } function countUniqueItems(){ if ($this-&gt;isEmpty()==false){ foreach($this-&gt;cart as $item){ if($item['id']){ $uniqueItems++; } } } return $uniqueItems; } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload