Reputation: 11
I have a database with rows containing an ID and a value.
I randomly insert these values between the numbers 1 and 100 as I insert records, so an ID has a random value. I use a while loop to go through the records and print them to screen. However, the way I want it is if the current value of the row in the while loop is LESS than the next value, then break out of the loop. Basically what I am asking is how to refer to the next record of a database while in a while loop working with the current, simply to check a value in it.
Upvotes: 1
Views: 79
Reputation: 46692
Try this:
$previousRow = mysql_fetch_assoc($result);
$previousRow['ID'] = -1;
while($currentRow = mysql_fetch_assoc($result))
{
if($currentRow['ID'] > $previousRow['ID'])
break;
echo $previousRow['Value'];
$previousRow = $currentRow;
}
Upvotes: 3
Reputation: 387707
Do it the other way round. Instead of breaking out based on the next element, just check on the next element based on the previous element (which you can simply store somewhere). I guess that the loop actually loops through the elements and does something; you can then just check the previous/current element first before doing anything and nobody will notice that you in fact loaded the next element.
Upvotes: 0
Reputation: 11087
$lastRecord = Array();
foreach($records as $thisRecord){
if($lastRecord['value'] < $thisRecord['value']){
// do what you need to do here
}
$lastRecord = $thisRecord;
}
This way you always keep the previous value stored
Upvotes: 0