Jump to content

[SOLVED] Adding values from while loop


chocopi

Recommended Posts

How do you go about adding all the values from a while loop. Here is my code:

 

<?php
$query = mysql_query("SELECT * FROM `Enemies` WHERE location='$location'") or die(mysql_error());
$num_row = mysql_num_rows($query) or die(mysql_error());
while($row = mysql_fetch_assoc($query))
{
$rarity = $row['rarity'];
$value = $rarity/100;
$value2 = $value*$num_row;
}
?>

 

So this code would loop through 3 times for example and I would like to add up all of the $value2's. Now I know there is a way to do this, but I can't remember :(

 

I think its along the line of $value2[0]+$value2[1]+$value2[2] or something like that, but as I said I can't remember.

 

If you can help it would be much appreciated,

 

Many Thanks,

 

~ Chocopi

Link to comment
Share on other sites

Cheers, but can you please show me how to use it with my code, seeing as I have never got around to learning foreach.

I sound like such a n00b. I really should know this, how embarassing

 

Thanks,

 

~ chocopi

 

 

Link to comment
Share on other sites

<?php
$query = mysql_query("SELECT * FROM `Enemies` WHERE location='$location'") or die(mysql_error());
$num_row = mysql_num_rows($query) or die(mysql_error());
$value2 = 0;//set it to 0 incase it was used before in your script - also means the variable is defined.
while($row = mysql_fetch_assoc($query))
{
$rarity = $row['rarity'];
$value = $rarity/100;
$value2 += $value*$num_row;//using the += operator works out $valeu*$num_row and adds it onto the current value of $value2. This allows you to add them all up
}
echo $value2;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.