Home › Forums › Back End › Simple PHP Pagination › Reply To: Simple PHP Pagination
August 25, 2014 at 9:38 am
#180540
Participant
The first function, to determine the offset for your query, would look something like this:
function pagination_getOffset( $page,$itemsPerPage ){
// make sure both args are integers
if(
! ctype_digit( (string)$page )
|| ! ctype_digit( (string)$itemsPerPage )
){
return 0;
}
return ($page - 1) * $itemsPerPage;
}
The second would create your pagination links. Since you only want prev/next links, it’s pretty simple:
function pagination_html( $page,$totalPages ){
// make sure both args are integers; current page cannot be greater than total pages
if(
! ctype_digit( (string)$page )
|| ! ctype_digit( (string)$totalPages )
|| $page > $totalPages
){
return false;
}
// this var will hold the HTML markup
$html = '';
// no "prev" link if on first page
if( $page > 1 ){
$html .= '<a href="?page='.($page - 1).'" rel="previous">Previous</a>';
}
// no "next" link on last page
if( $page < $totalPages ){
$html .= '<a href="?page='.($page + 1).'" rel="next">?Next</a>';
}
// done
return $html;
}
Usage would be like so:
<?php
// determine requested page, default to page 1
$page = isset( $_GET['page'] )?
$_GET['page']:
1;
// decide # of items per page
$limit = 30;
// determine offset for SQL statement
$offset = pagination_getOffset( $page,$limit );
// write your sql
$sql = "SELECT SQL_CALC_FOUND_ROWS ID, TITLE, COVER_URL FROM movies"
." ORDER BY id DESC"
." LIMIT $offset, $limit";
// do your query, etc..
// . . .
// use @BenWalker's suggestion to get total # of pages
$sql = "SELECT FOUND_ROWS()";
// do the query, assign result to $totalPages
// . . .
// get pagination links
$paginationHTML = pagination_html( $page,$totalPages );
// print where desired on page
echo $paginationHTML;