【问题标题】:How to sort MySQL results and then get the ID of the latest 10 datetimes in PHP如何对 MySQL 结果进行排序,然后在 PHP 中获取最近 10 个日期时间的 ID
【发布时间】:2015-11-18 15:57:23
【问题描述】:

如何从 MySQL $row[id]$row[timestamp] 获取 id 和时间戳结果并对结果进行排序并获取具有最新匹配时间戳的 id 数组? 因此,如果我的 MySQL 数据库中有这些数据,

3,2015-08-24 10:38:3134,2015-08-24 10:38:168,2015-08-24 10:38:51

我最终会得到一个数组,ID 的顺序是从最新到最旧的时间戳。

8,3,34

这是我的代码,省略了信息。

$servername = "IP:PORT";
$username = "USERNAME";
$password = "PASSWORD";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection to the database failed. Please try again. Error: " . $conn >connect_error);
}
$sql = "SELECT id, timestamp FROM posts ORDER BY timestamp DESC LIMIT 1,10;";
$result = $conn->query($sql);
$arrays = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $arrays[] = $row[id];
    }
}
foreach ($arrays as $key => $id) {
    $servername = "IP:PORT";
    $username = "USERNAME";
    $password = "PASSWORD";
    $dbname = "DB";
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection to the database failed. Please try again. Error: " . $conn->connect_error);
    }   
    $sql = "SELECT name,timestamp,text FROM posts WHERE id=\"" . $id . "\";";
    $result = $conn->query($sql);
    $arrays = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $date = date_create_from_format('Y-m-d H:i:s',$row[timestamp]);
            $timezone = new DateTimeZone('America/Los_Angeles');
            $timedate = date_timezone_set($date, $timezone);
            $finaltimedate = $timedate->format('Y-m-d h:i:s A');
            echo "<hr><h4>" . $row[name] . "<span style=\"float:right\">Time Posted: " . $finaltimedate . "</span></h4><br>";
            echo $row[text] . "<br>";
        }
    }
}

但是,当我重新加载页面时,它只显示 2 个相同的 ID=0 博客文章,而不是文章 0 和 4(只有 2 个文章)。

【问题讨论】:

  • 34 是最旧的,而不是最新的,等等
  • 这是一个select blah,blah from tablexxx order by dtColumn desc limit 10
  • 您可以尝试改进该问题的格式吗?

标签: php mysql sorting datetime


【解决方案1】:

如果我正确理解了您的问题,那么此查询应该适合您。

SELECT id, timestamp FROM TABLE_NAME ORDER BY timestamp DESC LIMIT 1,10;

【讨论】:

  • 抱歉问题不清楚,但感谢您的帮助。这对我有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 2016-01-31
相关资源
最近更新 更多