Part 12: Paginating your entries

Many people have asked how to paginate their blog’s front page so as to show the previous/next 5 entries, for example. This tutorial was originally posted by Amanda.

Please note: The Build-A-Blog series is an introduction to creating a simple blog script using PHP. These tutorials are meant to help you to learn PHP and MySQL and to use these to fetch and store data and display it on a web page. These tutorials should not be used ‘as is’ on a production website – especially if you are new to PHP and do not understand what you are doing. We would recommend that you try the B-A-B series on a safe, development environment – such as an offline installation of PHP and MySQL – so you can learn how everything works.

GWG and its staffers accept no responsibility for anything that may (or may not) happen to your site or server as a result of you using these tutorials – you do so AT YOUR OWN RISK.

  1. Add this code to the blog page that displays your entries after you have your MySQL connection information:
    $blog_postnumber = 5;

    The number after the = is the number of posts you want displayed on your blog.

  2. Next, add this underneath the above code:
    if(!isset($_GET['page'])) {
    	$page = 1;
    }
    else {
    	$page = (int)$_GET['page'];
    }
    $from = (($page * $blog_postnumber) - $blog_postnumber);
  3. Assuming you have kept the code of your blog index page as it is in the past tutorials, you should have this line near the top of the page:
    $sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT 5";

    You should change that code to the following:

    $sql = "SELECT * FROM php_blog ORDER BY timestamp DESC LIMIT $from, $blog_postnumber";
  4. The next step is to link the pages. To do this, add the following code to the bottom of your index page. It will calculate how many pages are needed based on how many posts you have, and how many you want to display on each page. It will then link the pages for you.
    $total_results = mysql_fetch_array(mysql_query("SELECT COUNT(*) as num FROM php_blog"));
    $total_pages = ceil($total_results['num'] / $blog_postnumber);
    if ($page > 1) {
        $prev = ($page - 1);
        echo "<a href=\"index.php?page=$prev\">&lt;&lt;  Newer</a> ";
    }
    for($i = 1; $i <= $total_pages; $i++) {
        if ($page == $i) {
            echo "$i ";
            }
    		else {
               echo "<a href=\"index.php?page=$i\">$i</a> ";
            }
    }
    if ($page < $total_pages) {
       $next = ($page + 1);
       echo "<a href=\"index.php?page=$next\">Older &gt;&gt;</a>";
    }

    For this last part to work, it’s assuming the page with your blog entry list is named index.php. If it’s not, you can change the index.php part in the last code. (It’s listed 3 times.)