Friday, March 17, 2017

How to Paginate Data With PHP

Its sometime we found that we need a pagination but its difficult to make it as easy as we think. Below is a code snippet to make an standard pagination system using PHP code. Its nothing but you have to pass some arguments to make a better pagination system.

$paginator = new stdClass();
$paginator->total = 444;
$paginator->limit = 10;
$paginator->page = 1;
$paginator->links = 5;
$paginator->list_class = "pagination";
$paginator->link = "/users/list?q=value;
 
$html = makePaginationHtml($paginator); 
 
function makePaginationHtml($paginator)
{
    $last = ceil($paginator->total / $paginator->limit);
    $start = (($paginator->page - $paginator->links) > 0) ? $paginator->page - $paginator->links : 1;
    $end = (($paginator->page + $paginator->links) < $last) ? $paginator->page + $paginator->links : $last;
    $html = '<ul class="' . $paginator->list_class . '">';
    $link = $paginator->link;

    if ($paginator->page > 1) {
        $html .= '<li class=""><a href="' . $link . '&limit=' . $paginator->limit;
        $html .= '&page=' . ($paginator->page - 1) . '">&laquo;</a></li>';
    }
    if ($start > 1) {
        $html .= '<li><a href="' . $link . '&limit=' . $paginator->limit . '&page=1">1</a></li>';
        $html .= '<li class="disabled"><span>...</span></li>';
    }
    for ($i = $start; $i <= $end; $i++) {
        $class = ($paginator->page == $i) ? "active" : "";
        $html .= '<li class="' . $class . '"><a href="' . $link . '&limit=';
        $html .= $paginator->limit . '&page=' . $i . '">' . $i . '</a></li>';
    }
    if ($end < $last) {
        $html .= '<li class="disabled"><span>...</span></li>';
        $html .= '<li><a href="' . $link . '&limit=' . $paginator->limit . '&page=';
        $html .= $last . '">' . $last . '</a></li>';
    }
    if ($paginator->page != $last) {
        $html .= '<li class=""><a href="' . $link . '&limit=' . $paginator->limit;
        $html .= '&page=' . ($paginator->page + 1) . '">&raquo;</a></li>';
    }
    $html .= '</ul>';
    return $html;
}

No comments:

Post a Comment