开发者

php session error

开发者 https://www.devze.com 2023-01-29 21:50 出处:网络
I was trying to make a shopping cart and got a code from web.. <?php session_start(); require_once \'class/Item.php\';

I was trying to make a shopping cart and got a code from web..

<?php
session_start();
require_once 'class/Item.php';
$product_id = $_REQUEST['i_id'];
$action = $_REQUEST['action']; 

$item= new Item();

if($product_id && !$item->p开发者_如何学CroductExists($product_id)) {
    die("Error. Product Doesn't Exist");
}

switch($action) { 
    case "add":
        $_SESSION['cart'][$product_id]++; 
    break;

    case "remove":
        $_SESSION['cart'][$product_id]--; 
        if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); 
    break;

    case "empty":
        unset($_SESSION['cart']); 
    break;
}
?>

but durring adding the first item to the cart it goes error. How can I correct it.

Error:

Notice: Undefined index: cart in C:\wamp\www\website\store_esp\addtocart.php on line 16

Notice: Undefined index: 2 in C:\wamp\www\website\store_esp\addtocart.php on line 16


Looks like you may be trying to manipulate variables that aren't setup yet. Make sure you're checking that $_SESSION['cart'][$product_id] exists before you do something on it:

if(!isset($_SESSION['cart'][$product_id]))
  $_SESSION['cart'][$product_id] = 0;

switch($action) {
...


Try changing this:

$_SESSION['cart'][$product_id]++;

to this:

if (isset($_SESSION['cart'][$product_id])) {
    ++$_SESSION['cart'][$product_id];
} else {
    $_SESSION['cart'][$product_id] = 1;
}


Without knowing the error, it's impossible to tell for sure. But using my deductive powers, I think the problem is here:

$_SESSION['cart'][$product_id]++;

It should be this:

if (isset($_SESSION['cart'][$product_id])) {
    $_SESSION['cart'][$product_id]++;
} else {
    $_SESSION['cart'][$product_id] = 1;
}

And you need to change this:

session_start();
// add this part
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}
require_once 'class/Item.php';
$product_id = $_REQUEST['i_id'];
$action = $_REQUEST['action']; 
0

精彩评论

暂无评论...
验证码 换一张
取 消