Change New Odometer to previous Odometer in next column

Hi, I am creating a Mileage System using MYSql and PHP. I am stuck here and need your prompt assistance. I am new here in this forum and in using PHP as well.
I have one table:
id unit_id Odomtr Prev.Odomtr
1 AAAAA 10000 0000
2 BBBBB 20000 0000
3 AAAAA 25000 10000
4 BBBBB 30000 20000

When I put Odometer reading, the system should make the last odometer reading as Prev.Odometer reading as shown above in Prev.Odometer. By default the Previous Odometer is zero.Later i want to calculate mileage and distance driven by liter.
It is very modestly requested that please help out me…

Thanks

For their FIRST record (e.g. new unit_id) you would do a standard insert query. From then on you can do it like so.

INSERT INTO odometer( unit_id, Odomtr, `Prev.Odomtr` ) 
SELECT 'AAAAA',
'10025',
Odomtr
FROM odometer
WHERE unit_id = 'AAAAA'
ORDER BY id DESC
LIMIT 1 

SO ‘AAAAA’ and ‘10025’ represent POST info and we use the select statement to get the value (Odomtr) for Prev.Odomtr.

PDO version

// PDO version 
$sql = "INSERT INTO odometer (unit_id, Odomtr, `Prev.Odomtr`)
SELECT :newunit_id, :Odomtr, Odomtr FROM odometer 
WHERE unit_id = :unit_id 
ORDER BY id DESC LIMIT 1";
$query = $db->prepare($sql);
$query->bindParam(":newunit_id", $unit_id);
$query->bindParam(":unit_id", $unit_id);
$query->bindParam(":Odomtr", $Odomtr);
$query->execute();

I am so grateful that you answered my question but can you please be more specific as I am just a begginer. Now i am using 3 queries together as you adviced: Please guide me…Thanks in advance
Note:
fu_id is being used instead of id
unit_id means truckno
I am inserting data into MySQL table using following 1st query successfully
Table name is: fuel_use_tbl

$sql = "INSERT INTO "
. "fuel_use_tbl (fu_id, unit_id, type, fuel_date, qty, odomtr, rate, driver_name,filled_by, fillup_time, time_zone ) VALUES "
. “(NULL, ‘$unitid’, ‘$cctype’, ‘$datepicker’, ‘$fuelqty’, ‘$odometer’, ‘$rate’, ‘$name’, ‘$filledby’, ‘$filltime’,‘$timezone’ )”;

      $sql="INSERT INTO fuel_use_tbl( unit_id, Odomtr, `Prev.Odomtr` ) 
            SELECT 'AAAAA','10025',odomtr FROM fuel_use_tbl WHERE unit_id = 'AAAAA' ORDER BY fu_id DESC LIMIT 1";
      
      
      $sql = "INSERT INTO fuel_use_tbl (unit_id, odomtr, `Prev.Odomtr`)
                SELECT :newunit_id, :odomtr, odomtr FROM fuel_use_tbl WHERE unit_id = :unit_id ORDER BY fu_id DESC LIMIT 1";
                $query = $dbc->prepare($sql);
                $query->bindParam(":newunit_id", $unit_id);
                $query->bindParam(":unit_id", $unit_id);
                $query->bindParam(":odomtr", $Odomtr);
                $query->execute();

Okay. We just change and add a few fields…
I was referring to an ether/or situation where you would do a standard insert if this is a new account.
This version is an all-in-one script solution in that it will attempt the insert/select query first looking for the unit_id. If the result is not found it will do a standard insert query. Hope I got all the fields changed correctly. :wink:

<?php
// PDO version 
$sql = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name,filled_by, fillup_time, time_zone, `Prev.Odomtr`)
SELECT :newunit_id, :type, :fuel_date, :qty, :odometer, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, Odomtr FROM fuel_use_tbl 
WHERE unit_id = :unit_id 
ORDER BY fu_id DESC LIMIT 1";
$query = $dbc->prepare($sql);
$query->bindParam(":newunit_id", $unitid);
$query->bindParam(":unit_id", $unitid);
$query->bindParam(":type", $cctype);
$query->bindParam(":fuel_date", $datepicker);
$query->bindParam(":qty", $fuelqty); 
$query->bindParam(":odometer", $odometer);
$query->bindParam(":rate", $rate);
$query->bindParam(":driver_name", $name);
$query->bindParam(":filled_by", $filledby);
$query->bindParam(":fillup_time", $filltime);
$query->bindParam(":time_zone", $timezone);
$query->execute();
$num = $query->rowCount();

//Above will fail if unit_id not found.
//We use $num to check and use regular insert
if($num === 0):
    
    //Default value for Prev.Odomtr
    $PrevOdomtr = "0000";
    
    $sql2 = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name, filled_by, fillup_time, time_zone, `Prev.Odomtr`)
    VALUES( :newunit_id, :type, :fuel_date, :qty, :odometer, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, :PrevOdomtr)";
    $query2 = $dbc->prepare($sql2);
    $query2->bindParam(":newunit_id", $unitid);
    $query2->bindParam(":type", $cctype);
    $query2->bindParam(":fuel_date", $datepicker);
    $query2->bindParam(":qty", $fuelqty); 
    $query2->bindParam(":odometer", $odometer);
    $query2->bindParam(":rate", $rate);
    $query2->bindParam(":driver_name", $name);
    $query2->bindParam(":filled_by", $filledby);
    $query2->bindParam(":fillup_time", $filltime);
    $query2->bindParam(":time_zone", $timezone);
    $query2->bindParam(":PrevOdomtr", $PrevOdomtr);
    $query2->execute();

endif;     

?>

Also, for above code to work you would need a PDO database connection.

//MySQL Database user name.    
$login = "";
//Password for MySQL.
$dbpass = "";
//MySQL Database name.
$dbname = ""; 
//Establish a connection
$dbc = new PDO("mysql:host=localhost;dbname=$dbname", $login, $dbpass);

A slight modification will give you mileage difference and fuel_ratio (miles per (gal,liter).
Note the field fuel_ratio DECIMAL( 10, 2 ).

<?php
// PDO version 
$sql = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name,filled_by, fillup_time, time_zone, `Prev.Odomtr`, mileage_diff, fuel_ratio)
SELECT :newunit_id, :type, :fuel_date, :qty, :odometer, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, Odomtr, ABS(:odometernew - Odomtr), ABS(ABS(:odometerratio - Odomtr) / :qtyratio) FROM fuel_use_tbl 
WHERE unit_id = :unit_id 
ORDER BY fu_id DESC LIMIT 1";
$query = $dbc->prepare($sql);
$query->bindParam(":newunit_id", $unitid);
$query->bindParam(":unit_id", $unitid);
$query->bindParam(":type", $cctype);
$query->bindParam(":fuel_date", $datepicker);
$query->bindParam(":qty", $fuelqty); 
$query->bindParam(":qtyratio", $fuelqty); 
$query->bindParam(":odometer", $odometer); 
$query->bindParam(":odometernew", $odometer); 
$query->bindParam(":odometerratio", $odometer);
$query->bindParam(":rate", $rate);
$query->bindParam(":driver_name", $name);
$query->bindParam(":filled_by", $filledby);
$query->bindParam(":fillup_time", $filltime);
$query->bindParam(":time_zone", $timezone);
$query->execute();
$num = $query->rowCount();

//Above will fail if unit_id not found.
//We use $num to check and use regular insert
if($num === 0):
    
    //Default values for Prev.Odomtr,mileage_diff,fuel_ratio
    $PrevOdomtr = "0";
    $mileage_diff = "0";
    $fuel_ratio = "0";
    
    $sql2 = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name, filled_by, fillup_time, time_zone, `Prev.Odomtr`, mileage_diff, fuel_ratio)
    VALUES( :newunit_id, :type, :fuel_date, :qty, :odometer, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, :PrevOdomtr, :mileage_diff, :fuel_ratio)";
    $query2 = $dbc->prepare($sql2);
    $query2->bindParam(":newunit_id", $unitid);
    $query2->bindParam(":type", $cctype);
    $query2->bindParam(":fuel_date", $datepicker);
    $query2->bindParam(":qty", $fuelqty); 
    $query2->bindParam(":odometer", $odometer);
    $query2->bindParam(":rate", $rate);
    $query2->bindParam(":driver_name", $name);
    $query2->bindParam(":filled_by", $filledby);
    $query2->bindParam(":fillup_time", $filltime);
    $query2->bindParam(":time_zone", $timezone);
    $query2->bindParam(":PrevOdomtr", $PrevOdomtr);
    $query2->bindParam(":mileage_diff", $mileage_diff);
    $query2->bindParam(":fuel_ratio", $fuel_ratio);
    $query2->execute();

endif;     
?>

I am really very thankful to you for sparing time for me. I did add your code and tried to enter data…Data entry was ok but I coudnt succeed to echo/show Prevodomtr. Please check my code. I am really very sorry for bothering you to go through the whole code…
mileage.php:

<?php include ( 'header.html');?>
<?php include ('selectdriver.php'); ?>
<?php include ('selectcc.php'); ?>
     


<form name="regisform" action="insertdata.php" method="POST" valign="top" >
        <h3> ADD RECORDS</h3>
        
   
        &nbsp; &nbsp;Select Car Carrier: <input type="text" name="unit_id" value="" /> <br/>  <br/>   
        &nbsp; &nbsp;Select C C Type :&nbsp; <select name="type" style="width: 173px; align: left">
            <option value="Long">Long</option>
            <option value="Single">Single</option>
            <option value="Rigid">Rigid</option>
          </select>

           <?php $query = "SELECT * FROM fuel_use_tbl WHERE type = ";  ?><br/> <br/> 

    &nbsp; &nbsp;Select Fuel Date:&nbsp; <input type="date"  name="fuel_date" value=""  />
 
        <br/> 
        <br/>    
              
      &nbsp; &nbsp;Fuel Qty: &nbsp;  &nbsp;  &nbsp;   &nbsp;   &nbsp;   &nbsp;   &nbsp;   <input type="text" name="qty" value="" /> <br/>    
              <br/>       
       
       &nbsp; &nbsp;Odometer :&nbsp;&nbsp;&nbsp;  &nbsp;   &nbsp;   &nbsp;   &nbsp; <input type="text" name="odomtr" value="" /> <br/>    
              <br/>        
        &nbsp; &nbsp;Fuel Rate :&nbsp;&nbsp;&nbsp;  &nbsp;   &nbsp;   &nbsp;   &nbsp; <input type="number" name="rate" value="1.7" />  
              <br/> 
        <br/> 
        &nbsp; &nbsp;Select Driver :&nbsp;&nbsp;&nbsp;  &nbsp;  <select name="name" style="width: 173px; align: left">
        
            <?php 
                foreach ($name as $value)
                {
                echo "<option>" . $value . "</option>";// this all part is an example to use aqn array and save data in dropdown box
                }
             ?>
            </select><br/><br/> 
   
        &nbsp; &nbsp;Filled By :&nbsp;&nbsp;&nbsp;  &nbsp;   &nbsp;   &nbsp;   &nbsp; <input type="text" name="filled_by" value="" /> <br/> <br/> 
        &nbsp; &nbsp;Filled up Time :&nbsp;&nbsp;&nbsp;<input type="text" name="fillup_time" value="" /> <br/> <br/> 
        &nbsp; &nbsp;Select TimeZone:  <select name="timezone" style="width: 173px;" align="right">
            <option value="AM">AM</option>
            <option value="PM">PM</option>
          </select>

           <?php $query = "SELECT * FROM fuel_use_tbl WHERE time_zone = ";  ?>
       
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; <input type="submit" value="Save" name="Save" /> <br/> <br/> <br/> <br/> 
 
        </form>
  
        <?php
        if($_SERVER['REQUEST_METHOD']=='POST')
        {
            $erArr = array();             
            require 'connectdb.php';

            $unitid= $_POST['unit_id'];
            $cctype=  isset($_POST['type']) ?$_POST['type']: '';
            $fuelqty= $_POST['qty']; 
            $odometer= $_POST['odomtr'];
            $rate= $_POST['rate'];
            $name= $_POST['name'];
            $filledby= $_POST['filled_by'];
            $filltime= $_POST['fillup_time'];
            $timezone= isset($_POST['timezone']) ?$_POST['timezone']: '';
            $datepicker= $_POST['fuel_date'];
         if(empty($_POST['rate']))
            {
                $erArr[] ="Mandatory field 'Name' is missing <br/>";
            }
                                   
            foreach ($erArr as $msg) //foreach is used here to process the array
                {
                    echo $msg;
                }   
          
$sql = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name,filled_by, fillup_time, time_zone, `PrevOdomtr`)
SELECT :newunit_id, :type, :fuel_date, :qty, :odomtr, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, odomtr FROM fuel_use_tbl 
WHERE unit_id = :unit_id 
ORDER BY fu_id DESC LIMIT 1";
$query = $dbc->prepare($sql);
$query->bindParam(":newunit_id", $unitid);
$query->bindParam(":unit_id", $unitid);
$query->bindParam(":type", $cctype);
$query->bindParam(":fuel_date", $datepicker);
$query->bindParam(":qty", $fuelqty); 
$query->bindParam(":odomtr", $odometer);
$query->bindParam(":rate", $rate);
$query->bindParam(":driver_name", $name);
$query->bindParam(":filled_by", $filledby);
$query->bindParam(":fillup_time", $filltime);
$query->bindParam(":time_zone", $timezone);
$query->execute();
$num = $query->rowCount();

//Above will fail if unit_id not found.
//We use $num to check and use regular insert
if($num === 0):
    
    //Default value for Prev.Odomtr
    $PrevOdomtr = "0000";
    
    $sql2 = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name, filled_by, fillup_time, time_zone, `PrevOdomtr`)
    VALUES( :newunit_id, :type, :fuel_date, :qty, :odomtr, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, :PrevOdomtr)";
    $query2 = $dbc->prepare($sql2);
    $query2->bindParam(":newunit_id", $unitid);
    $query2->bindParam(":type", $cctype);
    $query2->bindParam(":fuel_date", $datepicker);
    $query2->bindParam(":qty", $fuelqty); 
    $query2->bindParam(":odomtr", $odometer);
    $query2->bindParam(":rate", $rate);
    $query2->bindParam(":driver_name", $name);
    $query2->bindParam(":filled_by", $filledby);
    $query2->bindParam(":fillup_time", $filltime);
    $query2->bindParam(":time_zone", $timezone);
    $query2->bindParam(":PrevOdomtr", $PrevOdomtr);
    $query2->execute();

endif;     
      if(!empty($name))
             {
                $insertdb = mysqli_query($dbc, $sql);
                echo mysqli_error($dbc);//for trobleshooting eror
                if($insertdb ==1)
                {
                    echo"The Database has been updated successfully"  . "<br/>";
                }
                    else 
                        {
                echo "Please check the error";
                echo mysqli_error($dbc);
                }
              
             } 
            
        }
        
        ?>

<?Php
include 'connectdb.php';
//How would i able to print previous odometer column...plz assit
$count="SELECT fu_id, unit_id, type, fuel_date, odomtr, qty, rate, driver_name, filled_by,fillup_time, time_zone, sum(qty * rate ) as cost from fuel_use_tbl group by fu_id";


echo "<table border =1  bgcolor=white width=1200px >";
echo "<tr ><th>Fu_id</th><th>CC No</th><th>CC Type</th><th>Fuel Date</th><th>Odometer</th><th>Qty/Liters</th><th>Rate/RM</th><th>Cost/RM</th><th>Driver's Name</th><th>Filled by</th><th>Fillup Time</th><th>Time Zone</th></tr>";
foreach ($dbc->query($count) as $row) {
echo "<tr ><td>$row[fu_id]</td><td>$row[unit_id]</td><td>$row[type]</td><td>$row[fuel_date]</td><td>$row[odomtr]</td><td>$row[qty]</td><td>$row[rate]</td><td>$row[cost]</td><td>$row[driver_name]</td><td>$row[filled_by]</td><td>$row[fillup_time]</td><td>$row[time_zone]</td></tr>";
}
echo "</table>";
?>

     <?php include ( 'includes/footer.html');?>
To connect with database: **connectdb.php:**

I used both ways to connect but couldn't get previous odometer reading:

<?php

//DEFINE('USER','root');
//DEFINE('PASSWORD','123');
//DEFINE('HOST','localhost');
//DEFINE('DBNAME','mileage');

/*$login = "root";
//Password for MySQL.
$dbpass = "123";
//MySQL Database name.
$dbname = "mileage"; 
//Establish a connection
$dbc = new PDO("mysql:host=localhost;dbname=$dbname", $login, $dbpass);*/
$dbc = mysqli_connect('localhost', 'root',123 ,'mileage' );//main connection to database
mysqli_set_charset($dbc,'utf8');

?>

I restructured the layout a bit on this sample. Note extra fields in display and insert queries. Not sure what you have for selectdriver so I just queried same table for drivers. I’ve attached working PDO sample (change db connection values) and check sql file for table fields to compare with what you have.

<?php
include 'connectdb.php';
include 'selectdriver.php';


//POST processing
if($_SERVER['REQUEST_METHOD'] == 'POST'):
    /*
    echo "<pre>";
    print_r($_POST); 
    echo "</pre>"; 
    */      
        $erArr = array();
        $required = array(
          'unit_id' => 'Car Carrier'
        , 'type' => 'Car Carrier Type'
        , 'fuel_date' => 'Date'
        , 'qty' => 'Quantity'
        , 'odomtr' => 'Odometer'
        , 'rate' => 'Fuel Rate'
        , 'name' => 'Driver'
        , 'filled_by' => 'Filled By'
        , 'fillup_time' => 'Time'
        , 'timezone' => 'Time Zone'); 
        
        foreach($required as $field => $fieldlabel):
            if(!isset($_POST[$field]) || empty($_POST[$field])):
                $erArr[] ="Mandatory field '" . $fieldlabel . "' is missing <br/>";
            endif;        
        endforeach;
        
     if(empty($erArr)):
     
        $unitid = $_POST['unit_id'];
        $cctype =  isset($_POST['type']) ? $_POST['type'] : '';
        $fuelqty = $_POST['qty']; 
        $odometer = $_POST['odomtr'];
        $rate = $_POST['rate'];
        $name = $_POST['name'];
        $filledby = $_POST['filled_by'];
        $filltime = $_POST['fillup_time'];
        $timezone = isset($_POST['timezone']) ? $_POST['timezone'] : '';
        $datepicker = $_POST['fuel_date'];
        
        
        // PDO version 
        $sql = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name,filled_by, fillup_time, time_zone, `Prev.Odomtr`, mileage_diff, fuel_ratio)
        SELECT :newunit_id, :type, :fuel_date, :qty, :odometer, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, Odomtr, ABS(:odometernew - Odomtr), ABS(ABS(:odometerratio - Odomtr) / :qtyratio) FROM fuel_use_tbl 
        WHERE unit_id = :unit_id 
        ORDER BY fu_id DESC LIMIT 1";
        $query = $dbc->prepare($sql);
        $query->bindParam(":newunit_id", $unitid);
        $query->bindParam(":unit_id", $unitid);
        $query->bindParam(":type", $cctype);
        $query->bindParam(":fuel_date", $datepicker);
        $query->bindParam(":qty", $fuelqty); 
        $query->bindParam(":qtyratio", $fuelqty); 
        $query->bindParam(":odometer", $odometer); 
        $query->bindParam(":odometernew", $odometer); 
        $query->bindParam(":odometerratio", $odometer);
        $query->bindParam(":rate", $rate);
        $query->bindParam(":driver_name", $name);
        $query->bindParam(":filled_by", $filledby);
        $query->bindParam(":fillup_time", $filltime);
        $query->bindParam(":time_zone", $timezone);
        $query->execute();
        $num = $query->rowCount();
        
        //Above will fail if unit_id not found.
        //We use $num to check and use regular insert
        if($num === 0):
            
            //Default values for Prev.Odomtr,mileage_diff,fuel_ratio
            $PrevOdomtr = "0";
            $mileage_diff = "0";
            $fuel_ratio = "0";
            
            $sql2 = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name, filled_by, fillup_time, time_zone, `Prev.Odomtr`, mileage_diff, fuel_ratio)
            VALUES( :newunit_id, :type, :fuel_date, :qty, :odometer, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, :PrevOdomtr, :mileage_diff, :fuel_ratio)";
            $query2 = $dbc->prepare($sql2);
            $query2->bindParam(":newunit_id", $unitid);
            $query2->bindParam(":type", $cctype);
            $query2->bindParam(":fuel_date", $datepicker);
            $query2->bindParam(":qty", $fuelqty); 
            $query2->bindParam(":odometer", $odometer);
            $query2->bindParam(":rate", $rate);
            $query2->bindParam(":driver_name", $name);
            $query2->bindParam(":filled_by", $filledby);
            $query2->bindParam(":fillup_time", $filltime);
            $query2->bindParam(":time_zone", $timezone);
            $query2->bindParam(":PrevOdomtr", $PrevOdomtr);
            $query2->bindParam(":mileage_diff", $mileage_diff);
            $query2->bindParam(":fuel_ratio", $fuel_ratio);
            $query2->execute();
        
        endif;
    endif;
endif; 

//Grab display data
$data = array();
$sqldd="SELECT 
   fu_id
 , unit_id
 , type
 , fuel_date
 , odomtr
 , qty
 , rate
 , driver_name
 , filled_by
 , fillup_time
 , time_zone
 , sum(qty * rate ) as cost
 , `Prev.Odomtr`
 , mileage_diff
 , fuel_ratio 
 FROM fuel_use_tbl 
 GROUP BY fu_id";
$querydd = $dbc->prepare($sqldd);      
$querydd->execute();            
while($row = $querydd->fetch(PDO::FETCH_ASSOC)){
    $data[] = $row;
}
/*
echo "<pre>";
print_r($data); 
echo "</pre>"; 
*/

//After processing and queries add header
include 'header.html';
?>
    
<?php
// echo any errors
if(!empty($erArr)):
    foreach($erArr as $error):
        echo $error;
    endforeach;
endif; 
?> 


<div class="regisform">
    <form name="regisform" action="insertdata.php" method="post">
        <h3> ADD RECORDS</h3>
                
        <label for="unit_id">Select Car Carrier:</label>
            <input type="text" name="unit_id" id="unit_id" value="" />
              
        <label for="type">Select C C Type :</label>
            <select name="type" id="type">
                <option value="">-</option>
                <option value="Long">Long</option>
                <option value="Single">Single</option>
                <option value="Rigid">Rigid</option>
            </select>        
        
        <label for="fuel_date">Select Fuel Date:</label>
            <input type="date"  name="fuel_date" id="fuel_date" value="" />
        
        <label for="qty">Fuel Qty:</label>  
            <input type="text" name="qty" id="qty" value="" />
        
        <label for="odomtr">Odometer :</label>
            <input type="text" name="odomtr" id="odomtr" value="" />
            
        <label for="rate">Fuel Rate :</label>
            <input type="number" name="rate" id="rate" value="1.7" /> 
        
        <label for="name">Select Driver :</label>
            <select name="name" id="name">            
            <?php 
            foreach ($name as $value):
                echo '<option value="' . $value . '">' . $value . '</option>';
            endforeach;
            ?>
            </select>
        
        <label for="filled_by">Filled By :</label>
            <input type="text" name="filled_by" id="filled_by" value="" />
            
        <label for="fillup_time">Filled up Time :</label>
            <input type="text" name="fillup_time" id="fillup_time" value="" />
            
        <label for="timezone">Select TimeZone:</label>
            <select name="timezone" id="timezone">
                <option value="AM">AM</option>
                <option value="PM">PM</option>
            </select>
            
        <input type="submit" class="submit" value="Save" name="Save" /> 
    
    </form>
</div> 
        
<table class="display">
    <tr>
        <th colspan="15">Mileage Report</th>
    </tr>
    <tr>
        <td class="subheading">Fu_id</td>
        <td class="subheading">CC No</td>
        <td class="subheading">CC Type</td>
        <td class="subheading">Fuel Date</td>
        <td class="subheading">Odometer</td>
        <td class="subheading">Qty/Liters</td>
        <td class="subheading">Rate/RM</td>
        <td class="subheading">Cost/RM</td>
        <td class="subheading">Driver's Name</td>
        <td class="subheading">Filled by</td>
        <td class="subheading">Fillup Time</td>
        <td class="subheading">Time Zone</td>    
        <td class="subheading">Prev/Odomtr</td>
        <td class="subheading">Mile/Diff</td>
        <td class="subheading">MPL</td>
    </tr>
<?php 
foreach($data as $row):
    echo '<tr>
        <td>' . $row['fu_id'] . '</td>
        <td>' . $row['unit_id'] . '</td>
        <td>' . $row['type'] . '</td>
        <td>' . $row['fuel_date'] . '</td>
        <td>' . $row['odomtr'] . '</td>
        <td>' . $row['qty'] . '</td>
        <td>' . $row['rate'] . '</td>
        <td>' . $row['cost'] . '</td>
        <td>' . $row['driver_name'] . '</td>
        <td>' . $row['filled_by'] . '</td>
        <td>' . $row['fillup_time'] . '</td>
        <td>' . $row['time_zone'] . '</td>
        <td>' . $row['Prev.Odomtr'] . '</td>
        <td>' . $row['mileage_diff'] . '</td>
        <td>' . $row['fuel_ratio'] . '</td>
    </tr>'."\r";
endforeach;
?>
</table>
<?php
include 'footer.html';
?>

mileage.zip (3.7 KB) fuel_use_tbl.zip (680 Bytes)

Thank you so much for your prompt guidance. I update everything what you provided me. Although its a little difficult to follow each and every code what you did for me but I really appreciate for your instant help. With a very few changes i got able to connect as didn’t get any connectivity error. but when i insert data i receive following error and it doesn’t insert data in mysql and doesn’t echo as well: Please bear me i know i am very close to finish it. THANKS
Error:
Mandatory field ‘Driver’ is missing
Mandatory field ‘Time Zone’ is missing

select driver is using another table(sorry forgot to tell u)
now selectdriver.php is but its working…

<?php
//selectdriver.php
include 'connectdb.php';
$sqldriver = "SELECT DISTINCT(name) FROM drivers";
$name = array();
$querydriver = $dbc->prepare($sqldriver); 	 
$querydriver->execute();			
while($row = $querydriver->fetch(PDO::FETCH_ASSOC)){
	$name[] = $row['name'];
}
?>


**now insertdata.php is:**


<?php include ('selectdriver.php'); ?>


<?php
//POST processing
if($_SERVER['REQUEST_METHOD'] == 'POST'):
	/*
	echo "<pre>";
	print_r($_POST); 
	echo "</pre>"; 
	*/      
		$erArr = array();
		$required = array(
		  'unit_id' => 'Car Carrier'
		, 'type' => 'Car Carrier Type'
		, 'fuel_date' => 'Date'
		, 'qty' => 'Quantity'
		, 'odomtr' => 'Odometer'
		, 'rate' => 'Fuel Rate'
		, 'driver_name' => 'Driver'
		, 'filled_by' => 'Filled By'
		, 'fillup_time' => 'Time'
		, 'time_zone' => 'Time Zone'); 
		
		foreach($required as $field => $fieldlabel):
			if(!isset($_POST[$field]) || empty($_POST[$field])):
				$erArr[] ="Mandatory field '" . $fieldlabel . "' is missing <br/>";
			endif;		
		endforeach;
		
	 if(empty($erArr)):
	 
        $unitid = $_POST['unit_id'];
        $cctype =  isset($_POST['type']) ? $_POST['type'] : '';
        $fuelqty = $_POST['qty']; 
        $odometer = $_POST['odomtr'];
        $rate = $_POST['rate'];
        $name = $_POST['driver_name'];
        $filledby = $_POST['filled_by'];
        $filltime = $_POST['fillup_time'];
        $timezone = isset($_POST['time_zone']) ? $_POST['time_zone'] : '';
        $datepicker = $_POST['fuel_date'];
		
		
		// PDO version 
		$sql = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name,filled_by, fillup_time, time_zone, `Prev.Odomtr`, mileage_diff, fuel_ratio)
		SELECT :newunit_id, :type, :fuel_date, :qty, :odomtr, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, odomtr, ABS(:odometernew - odomtr), ABS(ABS(:odometerratio - odomtr) / :qtyratio) FROM fuel_use_tbl 
		WHERE unit_id = :unit_id 
		ORDER BY fu_id DESC LIMIT 1";
		$query = $dbc->prepare($sql);
		$query->bindParam(":newunit_id", $unitid);
		$query->bindParam(":unit_id", $unitid);
		$query->bindParam(":type", $cctype);
		$query->bindParam(":fuel_date", $datepicker);
		$query->bindParam(":qty", $fuelqty); 
		$query->bindParam(":qtyratio", $fuelqty); 
		$query->bindParam(":odomtr", $odometer); 
		$query->bindParam(":odometernew", $odometer); 
		$query->bindParam(":odometerratio", $odometer);
		$query->bindParam(":rate", $rate);
		$query->bindParam(":driver_name", $name);
		$query->bindParam(":filled_by", $filledby);
		$query->bindParam(":fillup_time", $filltime);
		$query->bindParam(":time_zone", $timezone);
		$query->execute();
		$num = $query->rowCount();
		
		//Above will fail if unit_id not found.
		//We use $num to check and use regular insert
		if($num === 0):
			
			//Default values for Prev.Odomtr,mileage_diff,fuel_ratio
			$PrevOdomtr = "0";
			$mileage_diff = "0";
			$fuel_ratio = "0";
			
			$sql2 = "INSERT INTO fuel_use_tbl (unit_id, type, fuel_date, qty, odomtr, rate, driver_name, filled_by, fillup_time, time_zone, `Prev.Odomtr`, mileage_diff, fuel_ratio)
			VALUES(:newunit_id, :type, :fuel_date, :qty, :odomtr, :rate, :driver_name, :filled_by, :fillup_time, :time_zone, :PrevOdomtr, :mileage_diff, :fuel_ratio)";
			$query2 = $dbc->prepare($sql2);
			$query2->bindParam(":newunit_id", $unitid);
			$query2->bindParam(":type", $cctype);
			$query2->bindParam(":fuel_date", $datepicker);
			$query2->bindParam(":qty", $fuelqty); 
			$query2->bindParam(":odomtr", $odometer);
			$query2->bindParam(":rate", $rate);
			$query2->bindParam(":driver_name", $name);
			$query2->bindParam(":filled_by", $filledby);
			$query2->bindParam(":fillup_time", $filltime);
			$query2->bindParam(":time_zone", $timezone);
			$query2->bindParam(":PrevOdomtr", $PrevOdomtr);
			$query2->bindParam(":mileage_diff", $mileage_diff);
			$query2->bindParam(":fuel_ratio", $fuel_ratio);
			$query2->execute();
		
		endif;
	endif;
endif; 

//Grab display data
$data = array();
$sqldd="SELECT 
   fu_id
 , unit_id
 , type
 , fuel_date
 , odomtr
 , qty
 , rate
 , driver_name
 , filled_by
 , fillup_time
 , time_zone
 , sum(qty * rate ) as cost
 , `Prev.Odomtr`
 , mileage_diff
 , fuel_ratio 
 FROM fuel_use_tbl 
 GROUP BY fu_id";
$querydd = $dbc->prepare($sqldd); 	 
$querydd->execute();			
while($row = $querydd->fetch(PDO::FETCH_ASSOC)){
	$data[] = $row;
}
/*
echo "<pre>";
print_r($data); 
echo "</pre>"; 
*/

//After processing and queries add header
include 'header.html';
?>
	
<?php
// echo any errors
if(!empty($erArr)):
	foreach($erArr as $error):
		echo $error;
	endforeach;
endif; 
?> 


<div class="regisform">
	<form name="regisform" action="insertdata.php" method="post">
		<h3> ADD RECORDS</h3>
				
		<label for="unit_id">Select Car Carrier:</label>
			<input type="text" name="unit_id" id="unit_id" value="" />
			  
		<label for="type">Select C C Type :</label>
			<select name="type" id="type">
				<option value="">-</option>
				<option value="Long">Long</option>
				<option value="Single">Single</option>
				<option value="Rigid">Rigid</option>
			</select>		
		
		<label for="fuel_date">Select Fuel Date:</label>
			<input type="date"  name="fuel_date" id="fuel_date" value="" />
		
		<label for="qty">Fuel Qty:</label>  
			<input type="text" name="qty" id="qty" value="" />
		
		<label for="odomtr">Odometer :</label>
			<input type="text" name="odomtr" id="odomtr" value="" />
			
		<label for="rate">Fuel Rate :</label>
			<input type="number" name="rate" id="rate" value="1.7" /> 
		
		<label for="name">Select Driver :</label>
			<select name="name" id="name">			
			<?php 
			foreach ($name as $value):
				echo '<option value="' . $value . '">' . $value . '</option>';
			endforeach;
			?>
			</select>
		
		<label for="filled_by">Filled By :</label>
			<input type="text" name="filled_by" id="filled_by" value="" />
			
		<label for="fillup_time">Filled up Time :</label>
			<input type="text" name="fillup_time" id="fillup_time" value="" />
			
		<label for="timezone">Select TimeZone:</label>
			<select name="timezone" id="timezone">
				<option value="AM">AM</option>
				<option value="PM">PM</option>
			</select>
			
		<input type="submit" class="submit" value="Save" name="Save" /> 
	
	</form>
</div> 
		
<table class="display">
	<tr>
		<th colspan="15">Mileage Report</th>
	</tr>
	<tr>
		<td class="subheading">Fu_id</td>
		<td class="subheading">CC No</td>
		<td class="subheading">CC Type</td>
		<td class="subheading">Fuel Date</td>
		<td class="subheading">Odometer</td>
		<td class="subheading">Qty/Liters</td>
		<td class="subheading">Rate/RM</td>
		<td class="subheading">Cost/RM</td>
		<td class="subheading">Driver's Name</td>
		<td class="subheading">Filled by</td>
		<td class="subheading">Fillup Time</td>
		<td class="subheading">Time Zone</td>	
		<td class="subheading">Prev/Odomtr</td>
		<td class="subheading">Mile/Diff</td>
		<td class="subheading">MPL</td>
	</tr>
<?php 
foreach($data as $row):
	echo '<tr>
		<td>' . $row['fu_id'] . '</td>
		<td>' . $row['unit_id'] . '</td>
		<td>' . $row['type'] . '</td>
		<td>' . $row['fuel_date'] . '</td>
		<td>' . $row['odomtr'] . '</td>
		<td>' . $row['qty'] . '</td>
		<td>' . $row['rate'] . '</td>
		<td>' . $row['cost'] . '</td>
		<td>' . $row['driver_name'] . '</td>
		<td>' . $row['filled_by'] . '</td>
		<td>' . $row['fillup_time'] . '</td>
		<td>' . $row['time_zone'] . '</td>
		<td>' . $row['Prev.Odomtr'] . '</td>
		<td>' . $row['mileage_diff'] . '</td>
		<td>' . $row['fuel_ratio'] . '</td>
	</tr>'."\r";
endforeach;
?>
</table>

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

Keep the connectdb on the main page like so. The “errors” “Driver is missing” etc are just the processing messages I set for required fields. I would think the driver name and “timezone” would be required fields but you can remove them from the required array if they are not required.

<?php
include 'connectdb.php';
include 'selectdriver.php';


//POST processing
if($_SERVER['REQUEST_METHOD'] == 'POST'):

DID you double check the database table for new fields mileage_diff, fuel_ratio? I included sql file to show what I have. As always, adjust to your needs, in both the DB and code.

HATS OFF!
Sorry it was my mistake, actually i exported my tbl from MYSQL as a back up and imported the same tbl assuming yours. Now inserted the correct one as you provided. EVERYTHING IS NEXT TO PERFECT. Just speechless for how much you helped me. As I am new here and that was my first question and how can i say bundle of thanks technically here.
Once again thanks and GBU always

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.