Really simple PHP pagination

Recently, the post count became so high for this blog that I had to implement pagination for them. Pagination can be quite troublesome sometimes, but eventually I came up with a really simple solution.

For the page, we simply use the querystring. In this example, let us use $_GET['page'] to initiallize the $page variable. If the GET var isn’t set we default to page 1.

$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;

Now, we want to figure out how many pages are in our query. For this, we can use the COUNT() SQL function, then divide the number returned by the amount of results per page we want.

$pages = implode(mysql_fetch_assoc(mysql_query(
    "SELECT COUNT(key) FROM table"
$pages = ceil($pages / 6);

Now, because we may have other GET variables set we want to preserve the querystring. To do this, we just assemble all the current variables (except the page one, of course) into a string.

$querystring = "";
foreach ($_GET as $key => $value) {
    if ($key != "page") $querystring .= "$key=$value&";

Then, we can loop through the pages, and echo out the links to them. Using a conditional or ternary operator we can also assign a different class to the current page.

echo "Pages: ";
for ($i = 1; $i <= $pages; $i++) {
    echo "<a " . ($i == $page ? "class=\"selected\" " : "");
    echo "href=\"?{$querystring}page=$i";
    echo "\">$i</a> ";

Then, to display only the results that are relevant to the current page we can use the LIMIT SQL clause, or in this case LIMIT (($page – 1) * 6), (6 because we have 6 results per page, and the first page needs to query from the 0th record).

$result = mysql_query("SELECT * FROM table LIMIT " . (($page - 1) * 6) . ", 6");