Please note, this is a STATIC archive of website technosmarter.com from July 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
 

How to display recent posts in Blog using PHP | Part 4


Fetch and display recent posts data using PHP

We are extending the first “ how to create a blog from beginning in PHP “ in details. In this tutorial, we will learn to display recent posts. Displaying recent posts in a blog is very important.We can fetch and display recent blog posts using PHP programming and MYSQL database. The latest posts also known as blog recent posts. To display recent posts MYSQL query has to be used as well as the order has to be used.
Let’s understand the Query –

 SELECT column1 column2 FROM table_name ORDER BY id DESC ;  


In the query above, you can see we are fetching two columns from the table using order by id and DESC.
Full form of DESC is descending order. The meaning of descending order, it selects the order from the last inserted id.
It will help you, to fetch the blog posts from the last inserted id number and you can display the recent blog posts .
We can use LIMIT to fetch data in the limit .
Let's have a look.

 SELECT column1 column2 FROM table_name ORDER BY id DESC LIMIT 6 ; 


You can set any number of limits for recent posts.


Now, back to the blog. Open your sidebar file and change the code.


blog/sidebar.php


<a href="#">Blog Recent post 1</a>
         <a href="#">Blog Recent post 2</a>
            <a href="#">Blog Recent post 3</a>
                <a href="#">Blog Posts List (Later Tutorial)</a>

 

Change the code above to –

 <?php
$sidebar = $db->query('SELECT articleTitle, articleSlug FROM techno_blog ORDER BY articleId DESC LIMIT 6');
while($row = $sidebar->fetch()){
    echo ' <a href="https://localhost/blog/'.$row['articleSlug'].'" >'.$row['articleTitle'].' </a >';
}
?>
 


Kindly check your URL path. It will fetch the 6 recent posts in the sidebar on every page of the blog .


Please Share

Recommended Posts:-