1

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.

1
  • What exactly is your question? Commented Nov 22, 2010 at 11:37

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would rather initialize $previousRow['ID'] with 0 or -1.
I rather meant: Do not fetch the first row but just initialize $previousRow['ID'] with some value.
@Gumbo, but then echo $previousRow['Value']; won't work. So, it has to be fetched.
0
$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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.