PHP分页功能有时会产生比所需更多的页面[最后一页为空]。 我该如何解决?

PHP分页功能有时会产生比所需更多的页面[最后一页为空]。 我该如何解决?

问题描述:

I just found a pagination function to display pages of images from a folder, however when paginating it the last few pages seem to be empty and I don't want this. Here's the code I'm working with:

<?php
    function show_pagination($current_page, $last_page){
        echo '<br><div>';
            echo ' <button type="button"><a href="?page=1">First Page</a></button> ';
            echo ' <button type="button"><a href="?page='.$last_page.'">Last Page</a></button> ';
        if( $current_page > 1 ){
            echo ' <button type="button"><a href="?page='.($current_page-1).'">&lt;&lt;Previous</a></button> ';
        }

        for($i = 1; $i <= $last_page; $i++){
            echo ' <button type="button"><a href="?page='.$i.'">'.$i.'</a></button> ';
        }

        if( $current_page < $last_page ){
            echo ' <button type="button"><a href="?page='.($current_page+1).'">Next&gt;&gt</a></button> ';
        }
        echo '</div><br>';
            echo '<div><p>Page '.$current_page.' out of '.$last_page.'</p></div><br>';
    }


    $folder = 'images/';
    $filetype = '*.*';
    $files = glob($folder.$filetype);
    $total = count($files);
    $per_page = 20;
    $last_page = (int)($total / $per_page);
    if(isset($_GET["page"])  && ($_GET["page"] <=$last_page) && ($_GET["page"] > 0) ){
        $page = $_GET["page"];
        $offset = ($per_page + 1)*($page - 1);
    }else{
        //echo "Page out of range showing results for page one";
        $page=1;
        $offset=0;
    }
    $max = $offset + $per_page;
    if($max>$total){
        $max = $total;
    }

    show_pagination($page, $last_page);
    for($i = $offset; $i< $max; $i++){
       $file = $files[$i];
       $path_parts = pathinfo($file);
       $filename = $path_parts['filename'];
       echo "<img src='$file' alt='$filename' style='border-style: solid;border-width: 2px;border-color: #4d94ff; margin: 5px'>";
    }
    show_pagination($page, $last_page);

        ?>

Any help resolving this minor issue will be greatly appreciated. However I'm calculating the last page seems to work in some cases, but doesn't work in all cases, I'm not sure why.

I' m fairly certain the problem lies in your offset - $offset = ($per_page + 1)*($page - 1).

Keep in mind that each page will show twenty items, not twenty one. For the first page, you want an index of 1. For the second, 21. For the third, 41. And so on.

As such, you'll only want to add the one after the page itself has been calculated. For this, you're probably looking for the following:

$offset = ($per_page * ($page - 1)) + 1;

Which equates to:

$offset = (20 * (1 - 1)) + 1; /* 1 for page 1 */
$offset = (20 * (2 - 1)) + 1; /* 21 for page 2 */
$offset = (20 * (3 - 1)) + 1; /* 41 for page 3 */