문제

I have been trying to create a very simple shopping cart and I'm having a problem with my $_SESSION array. This is for a school project and I'm trying to make it as simple as possible.

The error I'm getting is:

Notice: Undefined index: cart in C:\xampp\htdocs\Final\menu.php on line 31

Notice: Undefined offset: 5 in C:\xampp\htdocs\Final\menu.php on line 31

if(isset($_GET['id'])){
    $product_id = $_GET['id'];
    $_SESSION['cart'][$product_id]++;
    print_r($_SESSION);
    print "<br>";
    print_r($_GET);
}

Once I've added more than one item to a particular product_id, the error goes away. This is the way the tutorial I read explained to add items to the cart. Any suggestions?

도움이 되었습니까?

해결책

Looks like $_SESSION['cart'] does not yet exist. Since it's going to be an array, instantiate it first with:

if(!array_key_exists('cart', $_SESSION)) $_SESSION['cart'] = array();

Since you have not yet assigned anything to $_SESSION['cart'][$product_id], you'll get this type of error when trying to increment it. You may want to try:

$_SESSION['cart'][$product_id] = (array_key_exists($product_id, $_SESSION['cart'])) ? $_SESSION['cart'][$product_id] +1 : 1;

or as an if statement:

if(array_key_exists($product_id, $_SESSION['cart'])) $_SESSION['cart'][$product_id]++;
else $_SESSION['cart'][$product_id] = 1;

다른 팁

When you do $_SESSION['cart'][$product_id]++; you are actually doing:

$_SESSION['cart'][$product_id] = $_SESSION['cart'][$product_id] + 1;
//                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ generates warning if they keys do not exist yet
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assigns without problems if they keys do not exist yet

The assignment with newly created keys is not the problem, the warning is generated by php trying to get the actual value of $_SESSION['cart'][$product_id].

To solve this you should properly initialize the variable:

$_SESSION['cart'][$product_id] = isset($_SESSION['cart'][$product_id])
                                    ? $_SESSION['cart'][$product_id]++ 
                                    : 1;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top