Reputation: 25
My website is Career Tracker i want to add cart in my website in my local machine i got a error everytime so i tired.
i used XAMPP 1.8.1 [PHP: 5.4.7] i got a error everytime Notice: Undefined index: cart in functions.inc.php on line 4
i tired why my php veriable is undefined ?? $cart
this is my code i got error in 4 the line.
php undefined index error
<?php
function writeShoppingCart()
{
$cart = $_SESSION['cart'];
if (!$cart)
{
return 'My Cart (0) Items';
}
else
{
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<a href="cart.php">'.count($items).' item'.$s.' in your cart</a></p>';
}
}
?>
Upvotes: 0
Views: 910
Reputation: 313
just change your code as: (i normaly use for this case)
<?php
function writeShoppingCart()
{
if(isset($_SESSION['cart']))
{
$cart = $_SESSION['cart'];
if (!$cart)
{
return 'My Cart (0) Items';
}
else
{
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<a href="cart.php">'.count($items).' item'.$s.' in your cart</a></p>';
}
}
}
?>
may this help you...
Upvotes: 0
Reputation: 633
Accessing a variable before you've set it will throw a Notice.
Try checking if it exists first using the isset()
function.
Edited to note that you've also not started your session: session_start()
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.session-start.php
Upvotes: 0
Reputation: 1164
You should check whether cart index exists or not.
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : array();
Upvotes: 3
Reputation: 3806
Your session does not contain any index by the name "cart"
To make sessions available over multiple pages you need to activate sessions before any output by using the session_start
function.
Upvotes: 0