Display previous blog posts using PHP and MYSQL | Part 9

Previous blog posts can be easily fetched and displayed by PHP and MYSQL. Here we are learning to create a complete blog from the first tutorial"how to create complete blog from scratch in PHP" . In the previous tutorial, we learned to fetch and display the next blog posts. In this tutorial, we will learn to display previous blog posts. In a blog CMS, it would be easy to display the next post as well as the previous post. Buttons can also be made for next and previous posts, which are being used a lot nowadays.

The query of MYSQL has to be understood in order to fetch and display previous blog posts in PHP. In order to display previous rows data, the code will be opposite the code of the next posts. It becomes very easy. Let's understand the query of MYSQL.

 SELECT * from table_name where id<$current_page_id  order by id DESC limit 6 

In the query above, you can see that we are fetching the rows data less than the current page id.

table_name- Database table name

id- Database table id

current_page_id - We use current page id and less than(<) operator to fetch previous blog posts.

DESC- Fetch rows data in descending order.

Limit 6 – Set data limit

We are fetching rows data less than current page id in descending order and limit 6. You can specify any limit.

blog/show.php

Now, add the code lines after the recommended posts.

 

Previous Posts:

<?php // run query//select by current id and display the previous 5 posts $previous= $db->query("SELECT * from techno_blog where articleId<$articleIdc order by articleId DESC limit 5"); // look through query while($row1 = $previous->fetch()){ echo '

'.$row1['articleTitle'].'

'; } ?>

The above PHP code used MYSQL query for previous posts using the ID of the current blog post.

 

We are selecting rows data less than the current id using less than (<) operator. This tutorial is completely opposite to previous tutorials. In this way, the list of previous posts or blog posts can be displayed.

Recommended Posts:-

Previous Posts:-