php - Adding items to shopping basket using sessions -
this shopping basket , user can click add basket passing action=add variable across , selected switch statement. first time add item causes error (bottom). occurs first time leads me believe because session[cart] has not been created.
the variables set here:
if(isset($_get['id'])) { $item_id = $_get['id'];//the product id url $action = $_get['action'];//the action url } else { $action = "nothing"; } <?php if(empty($_session['user_loggedin'])) { header ('location: logon.php'); } else { switch($action) { //decide case "add": $_session['cart'][$item_id]++; //add 1 quantity of product id $product_id break; case "remove": $_session['cart'][$item_id]--; //remove 1 quantity of product id $product_id if($_session['cart'][$item_id] == 0) unset($_session['cart'][$item_id]); //if quantity zero, remove (using 'unset' function) - otherwise show zero, -1, -2 etc when user keeps removing items. break; case "empty": unset($_session['cart']); //unset whole cart, i.e. empty cart. break; case "nothing": break; } if(empty($_session['cart'])) { echo "you have no items in shopping cart."; }
adding items working fine first time add empty basket error below:
notice: undefined index: cart in h:\student\s0190204\ggj\basket.php on line 57 notice: undefined index: 1 in h:\student\s0190204\ggj\basket.php on line 57
that because $_session['cart'] variable isn't initialized first request. try below.
if(empty($_session['user_loggedin'])) { header ('location: logon.php'); } else { // added this... if(empty($_session['cart'])){ $_session['cart'] = array(); } switch($action) { //decide case "add": $_session['cart'][$item_id]++; //add 1 quantity of product id $product_id break; case "remove": $_session['cart'][$item_id]--; //remove 1 quantity of product id $product_id if($_session['cart'][$item_id] == 0) unset($_session['cart'][$item_id]); //if quantity zero, remove (using 'unset' function) - otherwise show zero, -1, -2 etc when user keeps removing items. break; case "empty": unset($_session['cart']); //unset whole cart, i.e. empty cart. break; case "nothing": break; } if(empty($_session['cart'])) { echo "you have no items in shopping cart."; }
Comments
Post a Comment