Harry Richards
Harry Richards

Reputation: 105

Calculating total

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?

Upvotes: 1

Views: 207

Answers (4)

kaizenCoder
kaizenCoder

Reputation: 2229

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'];
}

Upvotes: 0

Dante Ditan
Dante Ditan

Reputation: 34

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

Upvotes: 0

woofmeow
woofmeow

Reputation: 2408

You need to define your $tot variable

Put this before using it in your loop

$tot = 0;

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212522

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

Initialise

$tot = 0;

before your while loop

Upvotes: 7

Related Questions