Kuntal Basu
Kuntal Basu

Reputation: 830

php session error

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->productExists($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

Upvotes: 1

Views: 1297

Answers (3)

Jonah
Jonah

Reputation: 10091

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']; 

Upvotes: 1

wajiw
wajiw

Reputation: 12269

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) {
...

Upvotes: 2

scoates
scoates

Reputation: 853

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;
}

Upvotes: 1

Related Questions