2014-05-17 52 views
0

這是一個購物籃,用戶可以單擊添加到籃子,通過一個動作=添加變量,這是從switch語句中選擇的。但是,第一次添加項目會導致錯誤(底部)。這只是第一次發生,這導致我相信這是因爲會話[cart]尚未創建。將項目添加到使用會話的購物籃

的變量在這裏設置:

if(isset($_GET['id'])) 
{ 
$Item_ID = $_GET['id'];//the product id from the URL 
$action = $_GET['action'];//the action from the URL 
} 
else 
{ 
$action = "nothing"; 
} 




<?php 

if(empty($_SESSION['User_loggedin'])) 
{ 
header ('Location: logon.php'); 
} 
else 
{ 

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']); //unset the whole cart, i.e. empty the cart. 
    break; 

    case "nothing": 
    break; 
} 

if(empty($_SESSION['cart'])) 
{ 
echo "You have no items in your shopping cart."; 
} 

添加項目工作正常,但是我第一次添加了一些空籃我得到的錯誤如下:

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 
+0

到目前爲止沒有運氣答案:/ – Jayyf9

回答

0

那是因爲你第一個請求未初始化$ _SESSION ['cart']變量。嘗試下面的內容。

if(empty($_SESSION['User_loggedin'])) 
{ 
header ('Location: logon.php'); 
} 
else 
{ 

    // Added this... 
    if(empty($_SESSION['cart'])){ 
     $_SESSION['cart'] = array(); 
    } 

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']); //unset the whole cart, i.e. empty the cart. 
    break; 

    case "nothing": 
    break; 
} 

if(empty($_SESSION['cart'])) 
{ 
echo "You have no items in your shopping cart."; 
} 
0

如果你認爲你沒有創建$ _SESSION [「購物車」]變量,你可以簡單地檢查由

if (!isset($_SESSION['cart'])) 
{ 
    //Initialize variable 
} 

這個僞代碼將檢查變量未設置,然後執行一些後續代碼
(例如$_SESSION['cart'] = array();)。

相關問題