创建并添加到会话

时间:2014-05-18 13:51:42

标签: php mysql

我正在创建一个购物车,但在添加第一个项目时遇到了一些麻烦。购物车代码如下:

switch($action) { //decide what to do 

    case "add":

        $_SESSION['cart'][$Item_ID]++; //add one to the quantity of the product with id $product_id 
    break;

    case "remove":
        $_SESSION['cart'][$Item_ID]--; //remove one from the quantity of the product with id $product_id 
        if($_SESSION['cart'][$Item_ID] == 0) unset($_SESSION['cart'][$Item_ID]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. 
    break;

    case "empty":
        unset($_SESSION['cart'][$Item_ID]); //unset the whole cart, i.e. empty the cart. 
    break;

    case "nothing":
    break;
}

当我第一次添加一个项目(第一个添加到购物篮中)时,它会给我这些错误

Notice: Undefined index: cart in H:\STUDENT\S0190204\GGJ\Basket.php on line 59 Notice: Undefined index: 1 in H:\STUDENT\S0190204\GGJ\Basket.php on line 59

1 个答案:

答案 0 :(得分:1)

试试这个

 case "add":
 if(!isset($_SESSION['cart'][$Item_ID])){
  $_SESSION['cart'][$Item_ID]=0;
 }
  $_SESSION['cart'][$Item_ID]++;
  break;

这应该有效,因为当你试图第一次增加时$_SESSION['cart'][$item_ID]它没有设置

看到这个

$_SESSION['cart'][$Item_ID]++

等价
$_SESSION['cart'][$Item_ID] = $_SESSION['cart'][$Item_ID] + 1;
上面的表达式$_SESSION['cart'][$Item_ID]中的

未定义(在赋值的右侧)