Tutorials

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 on the forums by Amanda.

  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.)

Comments

Error Comments are closed for this entry.