0

Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance

Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public_html/ISD5/inc/functions.inc.php on line 3

You have no items in your shopping cart

<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
    return '<p>You have no items in your shopping cart</p>';
} else {
    // Parse the cart session variable
    $items = explode(',',$cart);
    $s = (count($items) > 1) ? 's':'';
    return '<p>You have <a href="cart.php">'.count($items).' item'.$s.'  in your shopping cart</a></p>';
}
}
1
  • The error is in functions.Inc.php not your code Commented Mar 14, 2012 at 20:26

6 Answers 6

1

If $_SESSION['cart'] isn't set, it throws that warning.

Try:

$cart = isset($_SESSION['cart'])?$_SESSION['cart']:false;
Sign up to request clarification or add additional context in comments.

Comments

1

Use "EMPTY":

<?php
function writeShoppingCart() {
    $cart = !empty($_SESSION['cart']);
    if (!$cart) {
        return '<p>You have no items in your shopping cart</p>';
    } else {
        // Parse the cart session variable
        $items = explode(',',$cart);
        $s = (count($items) > 1) ? 's':'';
        return '<p>You have <a href="cart.php">'.count($items).' item'.$s.'  in your       shopping cart</a></p>';
    }
}

Comments

1

This means that the key 'cart' does not exist in the $_SESSION superglobal array.

If it's alright for this value to not exist, you should be doing this:

$cart = false;
if (isset($_SESSION['cart'])) {
    $cart = $_SESSION['cart'];
}

You could use something called the ternary operator, in PHP, but since you're a beginner, I don't want to bombard you.

In development mode, it's alright to display errors but you should read more about disabling errors (error_reporting) and logging them (error_log()) so that they can be inspected without alarming visitors.

Comments

0

That means that your session does not contain $_SESSION['cart']

Try this instead:

$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : false;

Comments

0

Try this:

$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : NULL;

Comments

0

try initializing your $_SESSION with something like:

$_SESSION['cart'] = 0;    // zero items in cart

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.