Php/mysql compare previous result

Hello

I have a basic query that outputs the data into a while loop.
How can I compare each output with the previous row.

e.g

id username level
1 John 50
2 Mark 60
3 Sarah 12

I basically want to get the difference of the level data between the previous row.

So the output would basically be this.

id username level
1 John 50

difference: 10

2 Mark 60

difference: 15

3 Sarah 75

Also, the data is constantly changing and being deleted so I would like to avoid using the ID to do this.

The base code goes something like this. Tweak to your needs :slight_smile:


$lastrow = null;
$res = mysqli_query('SELECT id, username, level FROM some_table');
while ($row = mysqli_fetch_assoc($res))
{
    echo $row['id'], ' ', $row['username'], ' ', $row['level'], "\
\
";
    if (isset($lastrow)) {
        echo 'difference: ', $row['level'] - $lastrow['level'], "\
\
";
    }
    $lastrow = $row;
}

I don’t understand how Sarah goes from 12 to 75 in your example.

Also - are you getting these in the correct order from your database?