PHP MySQLi分页限制页数

时间:2016-06-07 16:57:28

标签: php mysqli paging

我有一个简单的PHP MySQLi分页脚本,每页显示5个条目。但是对于大型数据库条目,会显示相当多的页码。如何限制在我的分页中显示的页数?例如。一次10页: 第一个< 1 2 3 4 5 6 7 8 9 10> LAST

这是我的代码:

_this.cartStorage = cartStorage.cart;

1 个答案:

答案 0 :(得分:1)

您可以实现这样的分页器(简单版本,需要改进):

<?php

$totalPages = 28; //replace with database value
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$numPagesToShow = 10; //it's up to you

//avoid bug or trying to get page out of the bounds
if($currentPage > $totalPages) {
    $currentPage = $totalPages;
}

/* correct the number of pages to show on the left or right
 *   and always try to put the current page in the middle
 */
if($numPagesToShow >= $totalPages) {
    $numMaxPageLeft = 1;
    $numMaxPageRight = $totalPages;
} else {
    $pagesToShow = ceil($numPagesToShow/2);
    $numMaxPageLeft = $currentPage - $pagesToShow;
    $numMaxPageRight = $currentPage + $pagesToShow;

    if($numMaxPageLeft <= 0) {
        $numMaxPageRight = $numMaxPageRight - $numMaxPageLeft +1;
        $numMaxPageLeft = 1;
    } elseif($numMaxPageRight >= $totalPages) {
        $numMaxPageLeft -= ($numMaxPageRight - $totalPages);
        $numMaxPageRight = $totalPages;
    }
}

//loop to show all desired pages
for ($i=$numMaxPageLeft; $i<=$numMaxPageRight; $i++) {
    echo $i == $currentPage ? $i : "<a href='index.php?page=".$i."'>".$i."</a> ";
}