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>';
}
}
asked Mar 14, 2012 at 20:23
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;
answered Mar 14, 2012 at 20:25
0
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>';
 }
}
answered Mar 14, 2012 at 20:26
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.

answered Mar 14, 2012 at 20:30
0

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

Try this instead:

$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : false;
answered Mar 14, 2012 at 20:24
0

Try this:

$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : NULL;
answered Mar 14, 2012 at 20:25
0

try initializing your $_SESSION with something like:

$_SESSION['cart'] = 0; // zero items in cart
ThiefMaster
320k85 gold badges607 silver badges648 bronze badges
answered Mar 14, 2012 at 20:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.