Click button twice to update shopping cart?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tarantulus
    New Member
    • May 2007
    • 114

    #1

    Click button twice to update shopping cart?

    Hi Guys,

    I'm creating a simple shopping cart app.

    I have a button which launches $PHP_SELF? followed by variables (product id, qty, price etc)

    the cart works fine, apart from updating the first purchase, which requires two button presses...

    the code that is called when the button is pressed looks like this

    Code:
    if (!isset ($_SESSION['cart'])){
    			session_start();
    			
    		
    			if (isset ($_SESSION['cart'][$prod_id])){
    				$_SESSION['cart'][$prod_id]['qty'] += $qty;
    			} 
    			else{
    				$_SESSION['cart'][$prod_id] = array("qty"=>$qty,"price"=>$price);
    				
    			}
    		}
    so in simple terms:

    1 check if session is set, if not set it then move to next if
    2. if the product is in the cart, just add one to it, otherwise, add the product to the cart with a in the qty requested.

    Can you see anything wrong there??

    thanks in advance
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    As your code is now, this only works when condition [php]if (!isset ($_SESSION['cart'])){[/php] is met.

    You should start the session in the first statement if your script, i.e.[php]<?php
    session_start() ;
    ....
    [/php]Then you test whether the product exists in the session array and if so, increment it; if not add it to the session array.[PHP]
    if (isset ($_SESSION['cart'][$prod_id]))
    $_SESSION['cart'][$prod_id]['qty'] += $qty;
    else {
    $_SESSION['cart'][$prod_id]['qty'] = $qty;
    $_SESSION['cart'][$prod_id]['price'] = $price;
    }
    [/PHP]Ronald

    Comment

    Working...