PHP pagination function

paginationPHP

public function paging($limit,$numRows,$page){

    $allPages       = ceil($numRows / $limit);

    $start          = ($page - 1) * $limit;

    $querystring = "";

    foreach ($_GET as $key => $value) {
        if ($key != "page") $paginHTML .= "$key=$value&";
    }

    $paginHTML = "";

    $paginHTML .= "Pages: ";

    for ($i = 1; $i <= $allPages; $i++) {
        $paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
        $paginHTML .= "href=\"?{$querystring}page=$i";
        $paginHTML .= "\">$i</a> ";
    }

    return $paginHTML;

 }

This is my pagination function for MVC pattern implementation.But this function has not displayed next and prev links.

I need to return HTML variable for pagination with previous and next link to controller.

I passed these variable to this function from controller.

$limit,$numRows,$page

How can I get next and prev links to above function.

Best Answer

I have added some conditions in the loop itself.

Hope they work.

Try the following:

<?php
public function paging($limit,$numRows,$page){

    $allPages       = ceil($numRows / $limit);

    $start          = ($page - 1) * $limit;

    $querystring = "";

    foreach ($_GET as $key => $value) {
        if ($key != "page") $paginHTML .= "$key=$value&amp;";
    }

    $paginHTML = "";

    $paginHTML .= "Pages: ";

    for ($i = 1; $i <= $allPages; $i++) {
        if ($i>1) {
                    $prev = $i-1;
                    $paginHTML .= '<a href="?'.$querystring.'page='.$prev'">Previous</a>';
                }
                $paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
        $paginHTML .= "href=\"?{$querystring}page=$i";
        $paginHTML .= "\">$i</a> ";
                if ($i<$allPages) {
                    $next = $i+1;
                    $paginHTML .= '<a href="?'.$querystring.'page='.$next'">Next</a>';
                }
    }

    return $paginHTML;

 }
 ?>