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

Php 使用会话将项目添加到购物篮,php,Php,这是一个购物篮,用户可以单击addtobasket传递action=add变量,这是从switch语句中选择的。但是,第一次添加项目时会导致错误(底部)。这只是第一次发生,这让我相信这是因为会话[cart]尚未创建 变量设置如下: if(isset($_GET['id'])) { $Item_ID = $_GET['id'];//the product id from the URL $action = $_GET['action'];//the action from the URL }

这是一个购物篮,用户可以单击addtobasket传递action=add变量,这是从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.";
}

这是因为没有为第一个请求初始化$\u会话['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.";
}

如果您认为尚未创建$\u SESSION['cart']变量,只需通过

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

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

到目前为止没有找到答案:/
if (!isset($_SESSION['cart']))
{
    //Initialize variable
}