【问题标题】:How to sort MySQL entries by date in PHP? [duplicate]如何在 PHP 中按日期对 MySQL 条目进行排序? [复制]
【发布时间】:2019-10-03 12:24:09
【问题描述】:

我希望 MySQL 中的条目在我的网站上按日期(在我的情况下为 fDate)排序。这是表结构:

使用以下代码读取条目:

$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";
}

这导致我的网站看起来像这样:

现在我想要按日期排序的每一行的输出,以便日期最接近当前日期的行显示为第一行。 我是 MySQL 和 PHP 的新手,请问如何操作?

【问题讨论】:

标签: php mysql database sql-order-by


【解决方案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";
}

将 SQL 语句更改为

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

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多