Utku Dalmaz
Utku Dalmaz

Reputation: 10162

Limiting while loop

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

Upvotes: 2

Views: 10901

Answers (5)

JAL
JAL

Reputation: 21563

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

Upvotes: 1

symcbean
symcbean

Reputation: 48357

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.

Upvotes: 0

Daniel Vassallo
Daniel Vassallo

Reputation: 344291

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.

Upvotes: 9

nickf
nickf

Reputation: 546005

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
}

Upvotes: 3

Andomar
Andomar

Reputation: 238078

Just add a check for the number of rows:

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

Upvotes: 1

Related Questions