(PHP) Simple pagination

By | June 1, 2013

Here’s a simple way to paginate when getting large amounts of posts from the database.

<?php
// Connect to database. This is where $link comes from
include 'includes/db_connect.php'; 

// Find total number of rows in table
$result = mysqli_query($link, "SELECT COUNT(*) FROM example_table");
$row = mysqli_fetch_array($result);
$total_rows = $row[0];

// Set rows per page
$rows_per_page = 8;

// Calculate total number of pages
$total_pages = ceil($total_rows / $rows_per_page);

// Get current page
$current_page = (isset($_GET['p']) && $_GET['p'] > 0) ? (int) $_GET['p'] : 1;

// If current page is greater than last page, set it to last.
if ($current_page > $total_pages)
	$current_page = $total_pages;

// Set starting post
$offset = ($current_page - 1) * $rows_per_page;

// Get rows from database
$result = mysqli_query($link, "SELECT * FROM example_table LIMIT $offset, $rows_per_page");

// Print rows
echo '<hr>';
while($row = mysqli_fetch_array($result))
{
	echo $row['id'].'<br />';
	echo $row['text'];
	echo '<hr>';
}

// Build navigation
// Range of pages on each side of current page in navigation
$range = 4;

// Create navigation link for previous and first page.
if ($current_page > 1)
{
	$back = $current_page - 1;
	echo ' <a href="?p='.$back.'"> PREV</a> ';
	if ($current_page > ($range + 1))
		echo ' <a href="?p=1">1</a>... ';
}
else
	echo ' PREV ';

// Create page links, based on chosen range.
for ($i = $current_page - $range; $i < ($current_page + $range) + 1; $i++)
{
   if ($i > 0 && $i <= $total_pages)
      if ($i == $current_page)
         echo ' [<strong>'.$i.'</strong>] ';
	  else
         echo ' <a href="?p='.$i.'">'.$i.'</a> ';
}

 // Create navigation link for next and last page.
if ($current_page != $total_pages)
{
	$next = $current_page + 1;
	if (($current_page + $range) < $total_pages)
		echo ' ...<a href="?p='.$total_pages.'">'.$total_pages.'</a> ';

	echo ' <a href="?p='.$next.'">NEXT </a> ';
}
else
	echo ' NEXT ';
?>

Leave a Reply

Your email address will not be published.