1

I want entries in MySQL to be ordered by Date (fDate in my case) on my website. Here is the table structure:

subject / fDate / hDesc

The entries are read with this code:

$sql = "SELECT * FROM homework";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "<br> Fach: " . $row["subject"] . "<br> Bis zum: " . $row["fDate"]. "<br>" . $row["hDesc"]. "<br>";
    }
} else {
    echo "0 results";
}

And this results in my Website looking like this:

enter image description here

Now I would like the output of every row ordered by date, so that the row with the date closest to the current one is displayed as the first. I'm new to MySQL and PHP, so how can this be done?

1337HaxX0r
  • 53
  • 6
  • 2
    Just change your query to order it: `SELECT * FROM homework ORDER BY fDate`, using `ASC` or `DESC` to order as appropriate – Martin Oct 03 '19 at 12:27
  • Check this link [https://stackoverflow.com/questions/9511882/sorting-by-date-time-in-descending-order](https://stackoverflow.com/questions/9511882/sorting-by-date-time-in-descending-order) – Krishna Jangid Oct 03 '19 at 12:33

1 Answers1

1
$sql = "SELECT * FROM homework ORDER BY fDate DESC";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "<br> Fach: " . $row["subject"] . "<br> Bis zum: " . $row["fDate"]. "<br>" . $row["hDesc"]. "<br>";
    }
} else {
    echo "0 results";
}

Change the SQL statment to

SELECT * FROM homework ORDER BY fDate DESC (OR ASC)