Is there a way to limiting while loops when fetching data from mysql ?
$query = "SELECT * 
    FROM  `table` 
    WHERE user_id = '$id' 
    ORDER BY `ID` DESC";
$result = mysql_query($query);
while ($info = mysql_fetch_assoc($result)) {
    //stuff
}
Here i dont want to use mysql's LIMIT function, can i lim开发者_JAVA技巧it while loop other than that one ?
Thanks
You can always break the loop when it reaches its target. Otherwise you can use a for loop as Nick suggested.
$count = 0;
while ($count < 4 && $info = mysql_fetch_assoc($result)) {
    //stuff
    $count++;
}
However note that it may be a better idea to limit the result-set from the query with the LIMIT command.
Use a for loop. For example, to loop through up to five rows...
for ($i = 0; $info = mysql_fetch_assoc($result) && $i < 5; ++$i) {
    // do stuff
}
Just add a check for the number of rows:
while ($rowcount < 100 && $info = mysql_fetch_assoc($result)) {
    $rowcount += 1;
//stuff
}
You can use break to end a loop.
So, it could be
$result = mysql_query($query);
$count=0;
while ($info = mysql_fetch_assoc($result)) {
if($info=="what you're looking for"){ $count+=1; }
if($count >= 4){ break; }//break will exit the while loop
}
break php docs
You can always jump out of your PHP loop early - but you should be using the mysql LIMIT clause for this - the entire result set is fetched from the database and transfered to the client when you call mysql_query() potentially creating memory and performance problems.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论