Custom PHP Pagination

2019-08-21 08:33发布

问题:

I use the code below to do a "next" and "previous" navigation. It works but even when there is 1 entry the next button shows and when there are more than 20 entries and once they have been served the code shows next and previous. How can I make it so that the next button will only show if there are more than 10 and how do I show no next and previous button if there are no more results to show:

       if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {

        $startrow = 0;

       } else {
       $startrow = (int)mysql_real_escape_string($_GET['pg']);
       }

       echo '<a id=pgnvg href=
      "'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&   q='.($what).'">Next</a>';


       $prev = $startrow - 20;

       //only print a "Previous" link if a "Next" was clicked
       if ($prev >= 0)
       echo '<a id=pgnvg2 href="'.$_SERVER['PHP_SELF'].'?pg='.$prev.'">Previous</a>';

回答1:

you need to add a check on how many items are actually returned e.g:

if($itemAmount > 20) {
echo '<a id=pgnvg href=
      "'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&   q='.($what).'">Next</a>';
}

otherwise the next button will always display



回答2:

Assume that you have a variable $itemsCount containing the number of items into the recordset.

If you don't have one you can calculate it with a query like

count(*) FROM <wathever table or join> WHERE <list of conditions>

Further I would use a constant called ITEMS_ON_A_PAGE (Hope you will guess its content ;)

define ('ITEMS_ON_A_PAGE',20); // put it where more appropriate

...

if (!isset($_GET['pg']) or !is_numeric($_GET['pg'])) {
    $startrow = 0;
} else {
   // no need to issue a mysql query, you need an integer from a numeric variable
   $startrow = (int)$_GET['pg'];
}

$linkTemplate = '<a id="%s" href="?%s">%s</a>';
$nextPageFirstItem = $startrow + ITEMS_ON_A_PAGE;
$previousPageFirstItem = $startrow - ITEMS_ON_A_PAGE;

if ($itemsCount> $nextPageFirstItem) {
    echo printf($linkTemplate,
            'pgnvg',
            http_build_query(array('pg'=>$nextPageFirstItem,'q'=>$what)),
            'Next'
    );
}

if ($previousPageFirstItem >= 0) {
   echo printf($linkTemplate,
            'pgnvg2',
            http_build_query(array('pg'=>$previousPageFirstItem,'q'=>$what)),
            'Previous'
   );
}

Here there is the reference for the http_build_query that creates the query for you

There will be a lot of room to improve this code but, as a starting point, it would suffice ;)



回答3:

You might actually want to use a switch statement. Sometimes if statements stop working when you have too many of them and too many evaluate to be true. Just pay attention to when you want to break; vs not breaking (don't include break;).