Reputation: 141
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
}
Upvotes: 1
Views: 1392
Reputation: 32790
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";
Upvotes: 3
Reputation: 7207
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;
}
}
Upvotes: 0
Reputation: 298392
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.
Upvotes: 3