1

I want to fetch data from a database until a certain condition is satisfied. If this condition is satisfied I want to stop fetching after that point.

while($row=mysql_fetch_array($result1)){
$a1=$row['Count']
if($a1<100){
$w1=$a1
//Now I want to stop fetching data after this point and take the variable "$w1" out
}
HaK
  • 141
  • 2
  • 4
  • 13
  • simply use exit; after your condition is satisfied – Php Geek Mar 05 '13 at 07:05
  • 1
    Use `break;` to exit a loop. – Rikesh Mar 05 '13 at 07:05
  • 1
    @PavanK `exit` will stop everything, `break` is better – Hanky Panky Mar 05 '13 at 07:06
  • Yup i agree, use break; – Php Geek Mar 05 '13 at 07:10
  • try [http://stackoverflow.com/questions/3599548/fetch-only-n-rows-at-a-time-mysql](http://stackoverflow.com/questions/3599548/fetch-only-n-rows-at-a-time-mysql) or [this](http://stackoverflow.com/questions/573646/mysql-select-from-n-last-rows) may it will help you – M.I.T. Mar 05 '13 at 07:13
  • try [http://stackoverflow.com/questions/3599548/fetch-only-n-rows-at-a-time-mysql](http://stackoverflow.com/questions/3599548/fetch-only-n-rows-at-a-time-mysql) or [this](http://stackoverflow.com/questions/573646/mysql-select-from-n-last-rows) may it will help you – M.I.T. Mar 05 '13 at 07:13

3 Answers3

3

You can use break:

while ($row = mysql_fetch_array($result1)) {
    $a1 = $row['Count'];

    if ($a1 < 100) {
        $w1 = $a1;
        break;
    }
}

Or return it out of a function.

Blender
  • 289,723
  • 53
  • 439
  • 496
3

Best option is to give limits and where condition in your query

So that the query execution will be fast (You need to fetch less data).

Instead of fetching whole the data first and filtering it, Filter the data first and fetch it.

In your case : if you want to fetch first 100 records :

$sql = "SELECT * FROM table LIMIT 0,100";

And if you have any condition then,

$sql = "SELECT * FROM table WHERE field = '".$var."' LIMIT 0,100";
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0

Use break; or better you can use limit & where condition in your query

while($row=mysql_fetch_array($result1))
{
  $a1=$row['Count'];
  if($a1<100)
  {
     $w1=$a1; break;         
  }
}
Tapas Pal
  • 7,073
  • 8
  • 39
  • 86