will35010 Posted June 12, 2009 Share Posted June 12, 2009 This script is for calculating miles per gallon. I wrote everything but the calculation part. When it calculates mpg it shows a negative number always. Is something reversed? <?php //script to calculate fuel mileage //retrieve value from web form $vin = $_GET['vin']; //db connection info require('../opendb.php'); //Query to pull fuel data $sql = "SELECT mileage, gallons FROM fuel WHERE vin = '$vin' ORDER BY `date` DESC LIMIT 2"; //send query to database $result = mysqli_query($conn, $sql) or die('Error: ' . mysql_error()); $miles = ($gallons = array()); while ($r = mysqli_fetch_assoc($result)) { $miles[] = $r['mileage']; $gallons[] = $r['gallons']; } $mileGauge = array_pop($miles) - $miles[0]; array_shift($gallons); $tg = 0; foreach ($gallons as $v) { $tg += $v; } $mpg = $mileGauge / $tg; echo "This Vehicle's MPG: ".$mpg."<br />"; echo "Ignore negative numbers."; ?> Quote Link to comment Share on other sites More sharing options...
Mark Baker Posted June 12, 2009 Share Posted June 12, 2009 You're retrieving data from the database in descending date order, so the most recent record first, next oldest second. I'd expect the mileage to go up over time, so for the first record you retrieve it might be 1200 miles, for the second it might be 1000. When you calculate the mileage, you subtract the second (1000) record in the mileage array from the first (1200), giving -200. Don't know why you're calculating $tg in the way you are. If at 1000 miles on the clock there were 12 gallons in the tank, and by 1200 miles there were only 2 gallons, you discard the current level in the tank with array_shift($gallons), and loop?!? through the remaining single record in your array adding that value to $tg giving 12, ignoring any petrol left in the tank. Then you calculate mpg using the negative mileage with the incorrect fuel consuption -200 / 12 = -16.67 First off, get the correct (positive) mileage: $mileGauge = $miles[0] - array_pop($miles); Then calculate the actual fuel consumption: $tg = array_pop($gallons) - $gallons[0] without doing the array_shift($gallons); Finally, do your calculation as you are now $mpg = $mileGauge / $tg; Note that this calculation will be completely thrown if you fill up with petrol between measurements Quote Link to comment Share on other sites More sharing options...
will35010 Posted June 15, 2009 Author Share Posted June 15, 2009 Thank you. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.