Page 1 of 1

calculations inside of a loop [SOLVED]

Posted: Mon Dec 05, 2005 10:37 pm
by s.dot
I'm thinking that this code keeps adding onto itself inside of the loop, instead of doing a new check on each iteration through the loop. What this code is doing is checking that a person has not gone over their space limit when uploading multiple pictures. I allow 6 MB of space, and during each iteration of the loop, it should check to make sure they have not gone over that limit. However, I'm only at 30% of myspace usage, and even when adding small pictures it tells me I have gone over my limit. Does anyone see any problems?

Code: Select all

for($i=0;$i<10;$i++)
	{
		if($_FILES['filetoupload']['name'][$i])
		{
			$totalallowedsize = "6144000";
			$subpicsize = mysql_query("SELECT size FROM subpics WHERE username = '$theperson'");
			if(mysql_num_rows < 1)
			{
				$stotal = 0;
			} ELSE
			{
				while($subpicsizearray = mysql_fetch_assoc($subpicsize))
				{
					$stotal += $subpicsizearray['size'];
				}
			}
			$sql2query = mysql_query("SELECT size FROM albumpictures WHERE username = '$theperson'");
			if(mysql_num_rows($sql2query) < 1)
			{
				$atotal = 0;
			} ELSE
			{
				while($totalalbumsize = mysql_fetch_assoc($sql2query))
				{
					$atotal += $totalalbumsize['size'];
				}
			}
			$totalsize = $stotal + $atotal;
			if($totalsize > $totalallowedsize)
			{
				echo "<div class=\"error\"><p class=\"main\" align=\"center\">You're over your allowed space limit.  Consider deleting some pictures.</p></div><br /></td></tr></table>";
				require 'footer.php';
				die();
			}
      }
}

Posted: Mon Dec 05, 2005 11:20 pm
by Burrito
have you tried echoing $totalsize?

that might give you some clues...

Posted: Mon Dec 05, 2005 11:33 pm
by s.dot
OK, I decided to try uploading 4 pictures and printing $totalsize.. here are the results

Code: Select all

1656317
3323122
5006604
6723156
You're over your allowed space limit. Consider deleting some pictures.
The first one is correct, but the second one nearly doubles just by adding one picture (32 KB in size)? Third one is way off, 4th one is way off.

So I think it's adding the variables onto themselves instead of getting new numbers each time.

Posted: Mon Dec 05, 2005 11:39 pm
by Burrito
try setting $stotal and $atotal = 0 before your while loops.

since I assume you're inserting the size values to the db, they would be calculated on each iteration of the result set loop.

it's probably keeping those values on each iteration of the for loop....

Posted: Mon Dec 05, 2005 11:40 pm
by s.dot
hmm I fixed it. Not exactly how I wanted to fix it.. it feels like im "hacking" the script to make it work right

but I put

$stotal = 0;
$atotal = 0;

at the beginning of each iteration and it works good now. thanks burrito

Posted: Mon Dec 05, 2005 11:42 pm
by s.dot
haha nice response :) that's exactly what I did

great minds think alike ;d