如何排序MySQL结果,然后在PHP中获得最近10个日期时间的ID


How to sort MySQL results and then get the ID of the latest 10 datetimes in PHP

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

3,2015-08-24 10:38:31, 34,2015-08-24 10:38:16, 8,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篇文章)。

如果我正确理解你的问题,那么这个查询应该为你工作。

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