-1

I got a error message when I run my php

however the result is come out

this is my code

function cart() {
    foreach($_SESSION as $name => $value) {
        if ($value>0) {
            if (substr($name, 0, 5) == 'cart_'){
                $id = substr($name, 5, (strlen($name)-5));
                $get = mysql_query('SELECT id, name, price FROM products WHERE id=' .mysql_real_escape_string((int)$id));
                while ($get_row = mysql_fetch_assoc($get)){
                    $sub = $get_row['price'] * $value;
                    echo $get_row['name'].' x '.$value.' @ &pound'.number_format($get_row['price'], 2).' = &pound'.number_format($sub, 2).' <a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?delete='.$id.'">[Delete]</a><br />' ;
                }
            }
            $total += $sub;
        }
    }
    echo $total;
}
?>

I got a error message

 Notice: Undefined variable: total in C:\xampp\htdocs\shoppingcart\cart.php on line 54

which line 54 is

 echo $total;

what's wrong with my code??

I think I have defined the code in

 $total += $sub;

thanks for helping me :)

kapa
  • 77,694
  • 21
  • 158
  • 175

3 Answers3

2

To use a += it needs to be set first, else you get the warning.

Pop a $total=0; above it and you should be sweet.

function cart() {
    $total=0;
    // rest of your code...

You can read further about assignment operators here.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
2

If your $_SESSION is empty, the variable is never initialized, for example. Also, the operator += means add something to the variable - which triggers a notice if the variable is not set beforehand.

You could put $total = 0; before your loop:

$total = 0;
foreach($_SESSION as $name => $value) {
...

It's a good practice anyways to always initialize your variables, so you can save yourself from some bad surprises.

kapa
  • 77,694
  • 21
  • 158
  • 175
1

Add this as the first line of your function:

$total = 0;

Because now the first time your loop runs, $total is not a known var

Asciiom
  • 9,867
  • 7
  • 38
  • 57