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>';
}
}
-
The error is in functions.Inc.php not your codeToby Allen– Toby Allen2012年03月14日 20:26:15 +00:00Commented Mar 14, 2012 at 20:26
6 Answers 6
If $_SESSION['cart']
isn't set, it throws that warning.
Try:
$cart = isset($_SESSION['cart'])?$_SESSION['cart']:false;
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>';
}
}
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.
That means that your session does not contain $_SESSION['cart']
Try this instead:
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : false;
Try this:
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : NULL;
try initializing your $_SESSION with something like:
$_SESSION['cart'] = 0; // zero items in cart