tags:

views:

113

answers:

5

Hi

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 limit while loop other than that one ?

Thanks

+4  A: 

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.

Daniel Vassallo
so how will i know if it fetched for example 4 records ?
Ahmet vardar
Updated the answer with an example. However note that it may be a better idea to limit your loop from the SQL query.
Daniel Vassallo
it worked thanks
Ahmet vardar
+1  A: 

Just add a check for the number of rows:

while ($rowcount < 100 && $info = mysql_fetch_assoc($result)) {
    $rowcount += 1;
//stuff
}
Andomar
+3  A: 

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
}
nickf
A: 

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.

symcbean
i have some data that cant be filtered with mysql query and i need to check all fields thats why i am filtering them in while loop, so i needed to limit while loop
Ahmet vardar
A: 

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

Alex JL