While loop failing

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Trahb
Forum Commoner
Posts: 36
Joined: Sat Jan 30, 2010 9:09 pm

While loop failing

Post by Trahb »

I'm sure this is something extremely simple and I'm overlooking an obvious mistake ( like always ) but considering the fact that I can't seem to find it, I decided to ask for your help.

I'm trying to have it grab the last 20 entries from my SQL database, but it's only grabbing the last one... twenty times. Enough with the explanation, here's my code:

Code: Select all

$rank = 0;
    $query = mysql_query("SELECT * FROM `sites` ORDER BY `site_id` DESC");
    while($row = mysql_fetch_array($query))
    {
        while($rank < 20)
        {
            $rank++;
            doWork();
        }
    }
 
Thanks in advance ;)

Gahhhh. Found the mistake. Sorry to bother you guys.
For any of you that may want to know how it was fixed, all I did was replace

Code: Select all

 
while($rank < 20)
{
 
with

Code: Select all

 
if($rank <= 20)
{
 
and placed $rank++; outside of the if statement.
[/color]
M2tM
Forum Commoner
Posts: 41
Joined: Sat Feb 27, 2010 12:35 pm

Re: While loop failing

Post by M2tM »

Ok... But you're still looping through all the rows. Why not do this instead:

Code: Select all

 
     $rank  = 0;
     $query = mysql_query("SELECT * FROM `sites` ORDER BY `site_id` DESC");
     while($row = mysql_fetch_array($query) && $rank <= 20)
     {
          $rank++;
          doWork();
     }
 
this will cause the loop to stop running when the exit condition is met... Otherwise it'll keep looping, just do nothing.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: While loop failing

Post by John Cartwright »

Better to only query results you need.

Code: Select all

$query = mysql_query("SELECT * FROM `sites` ORDER BY `site_id` DESC LIMIT 20");
Post Reply