Pagination “Prev” and “Next” error

2019-05-22 13:37发布

问题:

Everything works fine but the "prev" and "next" links won't work. Once i click "prev" or "next" the page loads but no recent or old images show. The link quotes the "php?page=-1" for prev "php?page=1" and for next but like i said new images or old are shown only the first "20" and other first amount of $record_count

<?php
$dir = ".";
opendir($dir);
$file = ('uploaded/');

$files = glob("uploaded/*.*");
usort($files, function ($a, $b) {
return filemtime($b) - filemtime($a);
});

$record_count  = **20**;
$totla_pages   = ceil(count($files)/$record_count);

$home_script = $_SERVER['REQUEST_URI'];
    if($_SERVER['REQUEST_URI'] == $home_script) {
      $page = "";
}

$offset        = ($page-1)*$record_count;
$files_filter  = array_slice($files, $offset,$record_count);

foreach ($files_filter as $file) {
echo "<a href='$dir/$file'><img src='$file' style='height:180px;width:180px; border:2px solid black;  margin:20px 0px 10px  10px; *margin:10px 0px 10px 20px;'></a>";
}

if($totla_pages > 1){
   if($page != 1){
      echo '<a href="?page='.($page-1).'">Prev</a>';
   }
   if($page != $totla_pages){
      echo '<a href="?page='.($page+1).'">Next</a>';
   }
}
?>

回答1:

To start, you need to initialize your $page variable always and correctly, setting it to an integer.

To do that, you can check if a query variable is sent in and if not, set it to 1:

// somewhere at the top of your script
if (empty($_GET['page']))
{
  $page = 1;
}
else
{
  $page = (int) $_GET['page'];
}

You could also do some more checking on $_GET['page'] to make sure it is always a number larger than 0.