繁体   English   中英

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

[英]Adding items to shopping basket using sessions

这是一个购物篮,用户可以单击添加到购物篮,并在其中传递一个action = add变量,这是从switch语句中选择的。 但是,第一次添加项目会导致错误(底部)。 这仅是第一次发生,使我相信这是因为尚未创建session [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

这是因为您的$ _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.";
}

如果您认为尚未创建$ _SESSION ['cart']变量,则可以通过以下方式进行检查:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM