Linnea Anderson
Linnea Anderson

Reputation: 147

Pagination shows more pages

I cant figure this out and already spent hours on it. Pagination increment pages to the number of post pages means if 2 pages shows data then 2 blank pages shows if 3 pages shown data then it will go up to 3 more pages and so on and so forth. Any help would be appreciated here. pages increment to the number of posts showing means if number of posts show on 2 pages then pagination next button show 2 more blank pages if numbers of posts shows on 3 pages then it will blank pages increment to 3 pages

php:

<?php
         $page = (isset($_GET['page']) && $_GET['page'] > 0) ? (int)$_GET['page'] : 1;

        $perpage = 10;
        //$limit = ($page > 1) ? (((($page *2)+1)-3)* $perpage) - $perpage : 0;
        $limit = ((($page*2)+1)-3)*$perpage;

        $query = mysqli_query($dbc, "SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$limit}, {$perpage}");
        $records = mysqli_fetch_all($query);

        $total = mysqli_query($dbc, "SELECT FOUND_ROWS() as total");
        $total = mysqli_fetch_assoc($total)['total'];

        $pages = ceil($total/$perpage);
        ?>

<?php 
              if($page>1){
                ?>
                <a class="page-link" href="?page=<?php $pagep = $page -1; echo $pagep; ?>" tabindex="-1">Previous</a>
                <?php
              }
              ?>
            </li>
            <li class="page-item">
              <?php 
              if($page<$pages){
                ?>
                <a class="page-link" href="?page=<?php $pagen = $page +1; echo $pagen; ?>">Next</a>
                <?php
              }
              ?>

Upvotes: 1

Views: 867

Answers (1)

Jeff
Jeff

Reputation: 6953

Your calculation $limit = ((($page*2)+1)-3)*$perpage; doesn't result in what you need.

To fix this - for a normal pagination change it to

$limit = ($page-1)*$perpage;

But let's fix your variable names first, that makes it clearer how it works.
The Sql-Syntax for LIMIT is

[LIMIT {[offset,] row_count | row_count OFFSET offset}]

So let's rename the first var to $offset, the second to $rowCount

$offset = ($page-1)*$rowCount;

Now to your special case
"can you please tell me how to show only posts even like this .? first from 0 to 10 and then on the next page it will show from 20 to 40"
Then you need to also change the $perpage for each page:

// $page = 3; // set here only for testing
$rowCount = $page*10;
$offset = ($page-1)*$rowCount;
echo $offset.','.$rowCount;

// results:
// page=1 - 0,10
// page=2 - 20,20
// page=3 - 60,30


// So your SQL then will be 
"SELECT SQL_CALC_FOUND_ROWS * FROM final1 LIMIT {$offset}, {$rowCount}"

Upvotes: 2

Related Questions