Using PHP to show “Next” an “Previous” in paginati

2019-08-23 06:13发布

问题:

I am using the following code:

   $result = mysql_query("SELECT * FROM table LEFT JOIN table2 
   ON table.field = table2.field WHERE ( table.field = '$pid' ) 
   AND ( table.field5 LIKE '%$q%' OR table.field3 LIKE '%$q%' 
    OR table2.field2 LIKE '%$q%' )");


     if (empty($what)) {

      $countpls = "0";
      } else {

     $countpls = mysql_num_rows($result);
      }


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

$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 . '&q=' . ($what) . '">Previous</a>';
} else {
    echo "";
}
?>

I want the next to show only if there are more entries to show and previous only if there are more entries to circle back to. It works on the first page bt then on the last page Next shows despite teh fact that there are no more results to show.

I tried adding the 'else' but its still not working.

Any ideas?

回答1:

if($countpls > 0){
    $pg = $_POST['pg']?$_POST['pg']:1;

    //if it's not the first page...
    if($pg>1){
        echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg-1).'&q='.$what.'">Previous</a>';
    }
    //if you have more registers to show...
    if(($countpls-(($pg-1)*10))>10){
     echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg+1).'&q='.$what.'">Next</a>';
    }
}

In order to calculate your offset to use in queries, use this:

$offset = ($_POST['pg']-1)*10;


回答2:

It would help if you would provide the code that's setting $countpls. That might be the part that's causing the problem. Also, the else's are unnecessary. However, try this:

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


回答3:

I think it would do you good if you followed a tutorial to grasp the basic concepts. It even comes with the example that could either 1.) replace your current pagination or 2.) fix it.

http://www.phpfreaks.com/tutorial/basic-pagination