使用会话将项目添加到购物篮

时间:2014-05-17 12:08:26

标签: php

这是一个购物篮,用户可以点击添加到购物篮,传递一个action = add变量,这是从switch语句中选择的。但是,第一次添加项目时会导致错误(底部)。这只会在第一次出现时让我相信这是因为尚未创建会话[购物车]。

变量在此处设置:

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

2 个答案:

答案 0 :(得分: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.";
}

答案 1 :(得分:0)

如果您认为自己没有创建$ _SESSION [&#39; cart&#39;]变量,则可以通过

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

此伪代码将检查变量是否未设置,然后执行一些后续代码(例如$_SESSION['cart'] = array();)。