Page 1 of 1

While loop failing

Posted: Mon Mar 22, 2010 11:39 pm
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]

Re: While loop failing

Posted: Tue Mar 23, 2010 2:55 am
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.

Re: While loop failing

Posted: Fri Mar 26, 2010 7:44 pm
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");