1

I'm looking for some help on calculating a total from lots of subtotals from a database, the code I'm using is working to calculate it, but the PHP echos an error saying that

Notice: Undefined variable: tot in ..............\viewing.php on line 192

But it is still calculating the total cost and echoing it, any ideas on how to get rid of that error?

I am getting the subtotals from a database using this:

while($row=mysql_fetch_array($result)) { 
echo .....
$tot += $row['subtotal'];
}

At the bottom of the page, I've made it so it shows the total and its working, but its still giving me an error saying that the variable tot is undefined, any ideas?

Prix
  • 19,417
  • 15
  • 73
  • 132
Harry Richards
  • 105
  • 1
  • 9
  • 2
    Perhaps you can save yourself the trouble and have MySQL return the total for you: `SELECT SUM(my_column) FROM my_table WHERE ...`? – eggyal Aug 15 '13 at 23:53
  • If you don't want to see notices you can check out this page: http://stackoverflow.com/questions/2867057/how-do-i-turn-off-php-notices – Grim... Aug 15 '13 at 23:54

4 Answers4

6

It isn't an error, it's a notice!

Initialise

$tot = 0;

before your while loop

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    It's totally unrelated but "it's a notice" reminds me of this joke: A guy is standing on the corner of the street smoking one cigarette after another. A lady walking by notices him and says "Hey, don't you know that those things can kill you? I mean, didn't you see the giant warning on the box?!" "That's OK" says the guy, puffing casually "I'm a computer programmer" "So? What's that got to do with anything?" "We don't care about warnings. We only care about errors." – Langdi Aug 16 '13 at 00:06
1

You need to define your $tot variable

Put this before using it in your loop

$tot = 0;
woofmeow
  • 2,370
  • 16
  • 13
0
           $tot = 0;
          while($row=mysql_fetch_array($result)) { 
              echo .....
          $tot += $row['subtotal'];
           }
           echo $tot;
0

From the php documentation:

It is not necessary to initialize variables in PHP however it is a very good practice.

However it also says:

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables..

You can turn off notices at a variable level by doing this:

while($row=mysql_fetch_array($result)) { 
  @$tot += $row['subtotal'];
}

Having said that best practice is:

$tot = 0;
while($row=mysql_fetch_array($result)) { 
  $tot += $row['subtotal'];
}
kaizenCoder
  • 2,211
  • 6
  • 33
  • 64