2014-05-18 73 views
0

我正在創建購物車,並且在將第一項添加到它時遇到了一些麻煩。購物筐代碼如下:創建並添加到會話中

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

你忘了'在session_start()'? –

+0

No sessions_start()是否存在 – Jayyf9

+0

可以打印var_dump($ _ SESSION); –

回答

2

試試這個

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]++被equvivalent到

$_SESSION['cart'][$Item_ID] = $_SESSION['cart'][$Item_ID] + 1; 

上述表達式$_SESSION['cart'][$Item_ID]是不確定的(在分配的右手邊)

+0

我明白了,現在工作了,謝謝你的解釋。 – Jayyf9