Simple pagination for PHP

Today we are going to paginate.

There’s really simple ways, here I’ll show you the easier one and then another a bit more advanced.

The final result could be something like this:

paginacion

Here we set variables and returning values:

//pagination config
$query = "SELECT count(id) from tabledemo"; // we return the total of rows
$row=mysql_fetch_assoc(mysql_query($query));
$total_records = $row['Total'];//here is the total records
 
$records_per_page = 5;//how many results per page
$total_pages = ceil($total_records / $records_per_page);//total number of pages
$page = intval($_GET['p']);//current page
if ($page < 1 || $page > $total_pages) $page = 1;//be sure is a number
$offset = ($page - 1) * $records_per_page;//position 
 
$limit = " LIMIT $offset, $records_per_page";//sql we need to add IMPORTANT
//end config pagination
 
//showing data
$query	= "SELECT * from tabledemo  $limit "; //query
$result =	mysql__query($query);
 
while ($row=mysql_fetch_assoc($result))
{
		echo "showing data ".$row[0];
}

Simple pagination:

//Pagination
for ($i = 1; $i <= $total_pages; $i++) {
	echo "<a title='page $i' href='?p=$i'>$i - </a>";//link to page
}

Pagination with next, previous, first, en and shortener (in case there’s many pages).

$display_pages=10;//how many pages to display
 
echo "<a title='Start' href='?p=1'>< < Start</a> ";//Start
if ($page>1) echo "</a><a title='Previous' href='?p=".($page-1)."'> < < Previous </a> "; //Previous
 
for ($i = $page; $i < = $total_pages && $i<=($page+$display_pages); $i++) {
      if ($i == $page) echo "<strong>$i - </strong>";//not printing the link
      else echo "</a><a title='page $i' href='?p=$i'>$i</a> - ";//link
}
 
if (($page+$display_pages)< $total_pages) echo "..."; //etcetera...
if ($page<$total_pages) echo "<a title='Next' href='?p=".($page+1)."'> Next >>  ";//Next
echo "<a title='End' href='?p=$total_pages'>End >></a>";//end

Questions?

Related Posts Related Websites
Help sharing and Flatter me ;)

Share

2 Comments

  1. Kelvin says:

    Very useful! I used something similiar to splist search engine result…

  2. Chema says:

    simple but efficient ;)

Leave a Reply

Follow me