note 51450 added to control-structures.while

From: Date: Thu, 31 Mar 2005 04:14:52 +0000
Subject: note 51450 added to control-structures.while
Groups: php.notes 
Request: Send a blank email to php-notes+get-87230@lists.php.net to get a copy of this message
When using while() to roll over a MySQL query, you can waste pretty much time with a second while going over that query. As a matter of fact, while() kind of destroys the variable that contained the query-result after being rolled over. So you need put the query again into a variable. Example: <?php $all = @mysql_db_query($db,"SELECT * FROM person"); $maxscore = 0; while ($item = @mysql_fetch_object($all)) { //get the maximum score $tempqry = @mysql_db_query($db,"SELECT * FROM scores WHERE x_person = $item->id"); $cnttempqry = @mysql_num_rows($tempqry); if ($cnttempqry > $maxscore) $maxscore = $cnttempqry; } while ($item2 = @mysql_fetch_object($all)) { echo "Second while not parsed."; //do something with the individual scores in function of the $maxscore here. } /*Hereafter you might want to use this maximum score to set this as you new reference point, and base all the other scores on that one. Also to calculate averages, this system of the double while can be useful. In fact there are people who like to do all this things with special MySQL functions. Anyway, for the second while you wont get a glimpse of what's going on, just because the while condition isn't fulfilled, right. Only solution: reload the $all query, and the while will do its job.*/ $all = @mysql_db_query($db,"SELECT * FROM person"); while ($item2 = @mysql_fetch_object($all)) { echo "Second while succesfully parsed."; //do something with the individual scores in function of the $maxscore here. } ?> ---- Manual Page -- http://www.php.net/manual/en/control-structures.while.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+51450 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51450&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51450&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51450&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51450&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51450&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+51450&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#87230) next »