如何将最近(最新帖子)显示为博客列表中的第一个



大家好,我需要您在下面的 php 代码上的帮助。 我正在尝试将最近的(最新帖子(显示为列表中的第一个。我不知道如何使用按时间戳排序请帮助。 这是我下面的代码:

<!DOCTYPE html>  
<?php
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>Blogger</title>
<link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="container">
<a href="index.php" id="logo">B</a>
<ol>
<?php foreach ($articles as $article){?>
<li><a href="article.php?id=<?php echo 
$article['article_id'];>">
<?php echo $article['article_title'];?>
</a> 
- <small>
popsted <?php echo date('l jS', $article['article_timestamp']);>
</small>
</li>
<?php }?>
</ol>
<small><a href="admin">Admin</a></small>
</div>
</body>
</html>

下面是我的文章类代码,请帮助我如何放置/插入 ORDER BY 时间戳查询。谢谢!

<?php
class Article{
public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM articles");
$query->execute();
return $query->fetchAll();
}
public function fetch_data($article_id){
global $pdo;
$query = $pdo->prepare("SELECT * FROM articles WHERE article_id = ?");
$query->bindValue(1, $article_id);
$query->execute();
return $query->fetch();
}
}

?>

向 SQL 查询添加一个ORDER BY

$query = $pdo->prepare("SELECT * FROM articles ORDER BY article_timestamp DESC");

上面告诉MySQL按DESCending顺序按article_timestamp列对结果进行排序。如果你想要最旧的,它ASC就像在ASCending中一样。

您可以在手册中阅读有关对列进行排序的更多信息。

最新更新