Wouldn't it be cool if I could read my blog and just press a button to go to the next one? Well that's what I'm gonna add to the blog website.
I'll head over to the Bootstrap theme HTML and copy the blog pagination code and paste it under the blog content in the index.php. The buttons are called "older" and "newer". One button for older blogs and one for newer blogs.
The buttons don't link to anything because it's just placeholder HTML. The href attribute is a hashtag. So I'll replace that with a link to a blog with the id equaling to one less and one more from the blog id.
?id=<?= $blog['id'] + 1?>
This will increment blog id by one to the next blog and if the id is not valid the home page loads. If the id is anything other than a valid blog id it loads the home page.
But what if I delete a blog. The button will point to a blog id that doesn't exist bringing the user back to the home page and they won't why. The user will just be so confused they might just never come back to read your blog.
With SQL I can select the previous and next blog. So I'll go to my controller file and add a function for get_prev_blog and get_next_blog and pass in the current blog id.
So I'll go into my controller file and create a function for get_prev_blog and get_next_blog and pass in the current blog id.
SELECT * FROM blogs WHERE id > $current_blog_id LIMIT 1
This will select all blogs greater then the current blog id and limit it to one. However this only works for the next blog. The previous blog is a little different. Not only do we change the greater than to less than symbol but we also add
ORDER BY id DESC that way we don't just select the very first blog.
Also we don't need to query blogs that have future publish dates so we can just add an AND clause.
AND publish_date <= CURDATE()
But what if there is no newer blogs or previous blogs. That's where we check the variable and see if it was defined. If so we show the button. If not the button doesn't render.
Now we have blog pagination this is starting to act like a real blog website.