简体   繁体   中英

PHP MySQLi Pagination LIMIT issue

I am currently working on a pagination script for displaying records capped at 20 per page.

I have found a similar question on Stack Overflow, which had an example of how one would perform this. I've tried the code and made adjustments too, but I can't get it to function properly.

The code is:

$pages = ceil($rescnt['cnt']/$limit);

    $page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
    'options' => array(
        'default'   => 1,
        'min_range' => 1,
    ),
    )));
    $offset = ($page - 1)  * $limit;
    $start = $offset;
    $end = min(($offset + $limit), $rescnt['cnt']);

There are 41 records in the MySQL database (0 - 40).

The first page displays correctly, with a LIMIT 0,20 . However, the second page's limit is LIMIT 20,40 which actually returns 21 results.

The scripts calculates that there should be 3 pages in total (20 on P1, 20 on P2 & 1 on P3) however, P1 has 20 & P2 has 21. P3 is empty.

I have tried altering the calculation of the pages etc. but it still won't work. Could anyone please give me a little insight into this issue?

Thanks in advance.

FROM 21 to 40, rather than 20.

The LIMIT clauses are inclusive. It is from Record 20, count 20.

LIMIT 20,20 = 20,21,22,...37,38,39.

EDIT:

You will see LIMIT 0,20 shows 20 rows, but they start at zero. Rather like an array key, this perpetuates through the iterations.

BETTER:

You're updating the wrong columns.

First 20 results = LIMIT 0,20

next 20 results = LIMIT 19,20
final 20 results = LIMIT 39,20

LIMIT <start row>, <row count>

20 to 40 is 21 records. You have off by one bug. You should start off the next page with previous page last record plus 1. ie 21,40

Like 1 to 2 ie 1,2 is two records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM