Tech Notes

Simple Pagination Script for PHP

A ready-to-use PHP pagination function. Copy it into your project and adapt it as needed.

Here you go: copy and paste the code below and your pager will be ready. Feel free to modify it. This should save you some time ;)

<?php
/**
 * @author Sarath DR
 * @param $url - Page url
 * @param $total - Total Records
 * @param $interval - Number of result per page
 * @param int $page - Page number starting from 1
 * @return string
 *
 *
 */
function getPager( $url , $total, $interval, $page = 1  ){

    if( strpos($url , "?" ) !== false )
    {
        $url = $url."&";
    }
    else{
        $url = $url."?";
    }

    if( $total < $interval   ){
        return "";
    }

    $html = "<ol class='pagination'>";

    if( $page != 1 ){
        $html .= '<li><a href="'.$url.'page='.($page-1).'" >Prev</a></li>';
    }

    $pages = ceil( $total / $interval );

    for( $i=1 ; $i <= $pages ; $i++  ){
        $html .= '<li><a href="'.$url.'page='.$i.'" >'.$i.'</a></li>';
    }

    if( $page < $pages ){
        $html .= '<li><a href="'.$url.'page='.($page+1).'" >Next</a></li>';
    }

    return $html.= "</ol>";

}

echo getPager("/", 100 , 10 , 1 );

?>

View this code on GitHub