Forum Moderators: coopster

Message Too Old, No Replies

How do I calculate the difference of 2 MySql query Rows with PHP

Subtract the value of the current row from the previous row

         

russkern

12:22 pm on Sep 25, 2008 (gmt 0)

10+ Year Member



I have multiple rows returned through a MySql query.

As part of my data output for row 2, 3, 4, etc.., I want to present the difference of a value between the current row and the previous row.

for instance if the first row's value is 2 and the second row's value is 3... I want to echo 1.

How do I go about getting the value of the previous row... seems like it should be pretty straight forward, but I'm having a tough time even writing out the logic for it...

Thanks in advance

Russ

d40sithui

3:57 pm on Sep 25, 2008 (gmt 0)

10+ Year Member



hi,
when you are looping through your result set, save the value in a temporary varariable. use that to compare to the next row assuming the data you get is an integer. see below (havent tested).


$previousRow = 0; //initiates value for preceeding row
while($row = mysql_fetch_assoc($result)){
$currentRow = $row['fieldName']; //gets current row
$difference = $currentRow - $previousRow; //gets difference between the two variables
echo "\$difference = $difference<br>\n";
$previousRow = $currentRow; //reassigns previous row
}

this is probably the easier way. alternative is to use mysql_data_seek().

russkern

6:00 pm on Sep 25, 2008 (gmt 0)

10+ Year Member



That solution worked wonderfully... I was working toward something like that but couldn't quite get it...

Excerpt from my code is below to share.


$prev_mile = 0;
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$curr_mile = $row[1];
$diff = $curr_mile-$prev_mile;

if($diff==$row[1]){
$mpg="0";
} else {
$mpg = $diff/$row[2];
}

echo $mpg;

Thank you