Roshan Senanayake
Roshan Senanayake

Reputation: 11

Cannot sort by including the date

When I enter the vehicleID and Date, the records must be sorted by using both vehicle ID and Date, however it doesn't get sorted from the Date but only with the vehicleID. How can I achieve this ?

if ($vid != null && $datepicker != null) {
    $conn = new Db();
    $sql = "SELECT * FROM trip_details where vehicle_id = '".$vid."' AND date_t = '".$datepicker."'";
    $result = $conn->query($sql);
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td> ". $row["trip_id"]."</td>";
        echo "<td> ". $row["vehicle_id"]."</td>";
        echo "<td> ". $row["total_trip_km"]."</td>";
        echo "<td> ". $row["predict_fual"]."</td>";
        echo "<td> ". $row["date_t"]."</td>";
        // echo "<td><input type=\"submit\" value=\"view map\"></td>";
        echo "</tr>";
    }
}

Upvotes: 0

Views: 58

Answers (3)

Ankur Garg
Ankur Garg

Reputation: 605

Order by needs to define to get the desired result.

try this

 $sql="SELECT * FROM trip_details where
 vehicle_id='".$vid."' AND date_t='".$datepicker."' 
 ORDER BY vehicle_id DESC,date_t DESC";

Upvotes: 0

Guru0008
Guru0008

Reputation: 54

to sort you data by the columns you have define the name of columns in order by clause with order Acs(ascending) or Desc (descending)

e.g.

order by desc column1, asc column2

Upvotes: 0

Mureinik
Mureinik

Reputation: 312279

SQL makes no guarantee on the order results are returned from a select query unless you explicitly add an order by clause, so the fact that you observe the returned records sorted by the vehicle_id is coincidental. You need to add an order by clause to the query:

ORDER BY vehicle_id, date_t

Upvotes: 1

Related Questions