PHP中一个总和的未定义变量[关闭]

I am making a shopping cart in php, its almost done and now i'm making the total of all items in the cart with:

while ($data=mysql_fetch_array($result)){

$total=$price+$total;

}

It returns "Undefined variable:total" but it works anyways and i got the correct result. Its very strange and i don't want this error showing up.

When i define the variable like in the example below it doesn't give me the right result, just gives me the last value of the '$price' variable and not the sum.

$total=0;
$total=$price+$total;

Can someone give me a hint, seems very simple to solve but i can't do it. Thanks in advance.

move your

$total=0; 

above your while and the undefined error should be gone. The reasons is clear, you're trying to add $price to undefined variable.

Move total above the while. and then use += for less verbose code.

$total=0;
while ($data=mysql_fetch_array($result)){
  $total+=$price;
}