Page 1 of 1

math issue

Posted: Mon Apr 04, 2016 9:40 pm
by cybershot
I have been working on this database for a while. It's to calculate my gas usage. I can't figure out how to do the math. I want to subtract the mileage to get the amount of miles I drove on each tank of gas. Here is what I have so far

Code: Select all

while($row = mysqli_fetch_assoc($result)){
	$date = str_replace('-','/', $row['date']);
	echo "<tr><td>" . $row['id'] . "</td><td>" . $row['miles'] . '</td><td>' . '$' . number_format($row['amount'], 2) . '</td><td> ' . $row['gallons'] . '</td><td> ' . $date . "</td></tr>";
}
This ends up with a nice little table that shows the id, my mileage at the time of fill up, the amount of the fill up, the amount of gallons purchased and the date of purchase. I have 5 months of data in my table. How do I write it so that the $row['miles'] can be subtracted by the next entry? It's actually kind of backwards because as it is, it would give me a negative number if I did the math. My attempt ended up giving me all 0's. Here is what the first 3 rows look like in my table

ID MILES AMOUNT GALLONS DATE
90 146547 $31.70 10.432 2015/07/25
103 147117 $28.42 10.226 2015/08/12
100 147419 $27.80 10.186 2015/08/22

so 146547 needs to be subtracted from 147117 and 147117 needs to be subtracted from 147419 and so on..

Re: math issue

Posted: Mon Apr 04, 2016 10:24 pm
by Christopher
It might be easier to read all the rows in first:

Code: Select all

$rows = array();
$n = 0;
while($row = mysqli_fetch_assoc($result)){
        $rows[$n] = $row;
        ++$n;
}

$miles = $row[0]['miles'];
for ($i=0; $i<$n; ++$i) {
	$date = str_replace('-','/', $row[$i]['date']);
	echo "<tr><td>" . $row[$i]['id'] . "</td><td>" . ($row[$i]['miles'] - $miles) . '</td><td>' . '$' . number_format($row[$i]['amount'], 2) . '</td><td> ' . $row['gallons'] . '</td><td> ' . $date . "</td></tr>";
        $miles = $row[$i]['miles'];
}
PS - you should add a check for if no rows are returned.

Re: math issue

Posted: Tue Apr 05, 2016 9:19 pm
by cybershot
I tried your code and it didn't work. It returned zeroes for 2 results and the rest of them vanished. I think I see what you were trying to do though but I don't understand it all.

Re: math issue

Posted: Tue Apr 05, 2016 10:59 pm
by Christopher
cybershot wrote:I tried your code and it didn't work. It returned zeroes for 2 results and the rest of them vanished. I think I see what you were trying to do though but I don't understand it all.
Looked more like a programming test when I checked the code a second time. You should have caught it!

The problems is: the first loop populates the array $rows (using $row a temp variable). But in the second loop the code uses $row not $rows. Change $row to $rows in the second loop and it should work.

Re: math issue

Posted: Wed Apr 06, 2016 8:24 pm
by cybershot
I did do that last night for one of the variables but didn't see the result. When I changed the all, it worked. Thank you.