ShiggyDooDah
ShiggyDooDah

Reputation: 507

php pagination - how do i limit the number of pages show

I am having difficulties understanding how to limit the number of pages with pagination. I am trying to list my articles in my DB but I have over 500 pages! I would only like to show a max of about 15 page numbers at a time. I can't seem to understand the answers given in the other questions.

Here is my code for the Pagination:

<?php 
    require 'core/init.php';

    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    if(!isset($_GET['page'])){
        $_GET['page'] = 1;
    }
    if(! (int)$_GET['page']){
        $_GET['page'] = 1;
    }
    if($_GET['page'] < 1){
        $_GET['page'] = 1;
    }
    $perPage = 18;
    $start = ($page > 1) ? ($page * $perPage) - $perPage : 0; 

    $articles = DB::getInstance()->query("SELECT SQL_CALC_FOUND_ROWS * FROM articles ORDER BY added DESC LIMIT {$start}, {$perPage}");

    foreach($articles->results() as $article){ ?>
        <div class="article-container">
            <h2><?php echo $article->title; ?></h2>
        </div>
    <?php 
    }

    // pagination 

    $total = DB::getInstance()->query("SELECT FOUND_ROWS() as total");

    $total = $total->results()[0];

    foreach ($total as $total => $value) {

    }

    $pages = ceil($value / $perPage);
    $maxpage = 15;
?>
<div class="pagination"> 
    <?php if($_GET['page'] >= 2){
        echo '<a href="?page=' . ($_GET['page'] -1) . '" class="paginationButton">Prev</a>';
    }
    for ($i=1; $i <= $pages; $i++) : ?>
        <a href="?page=<?php echo $i; ?>" <?php if($page === $i) { echo 'class="pageSelected"'; } ?>><?php echo $i; ?></a>
    <?php   endfor;
        if((int)$_GET['page'] != $i - 1 ){
            echo '<a href="?page=' . ($_GET['page'] +1) . '"class="paginationButton">Next</a>';
        }
    ?>
</div>

This works as expected but it only spits out the number of pages from 1 to 500. What is the best/easiest way to show something like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 ... >

?

Upvotes: 2

Views: 3752

Answers (1)

Richard
Richard

Reputation: 1055

You need to change your for-cycle, the starting point and ending point

$count = 9;
$startPage = max(1, $page - $count);
$endPage = min( $pages, $page + $count);
for($i = $startPage; $i < $endPage; $i++) {
    // write out the link to the page
}

then if the page is 250 it will show only 241, 242, ..., 250, ..., 257, 258

Upvotes: 2

Related Questions