简体   繁体   中英

CakePHP: Numbered Paginated Results

The title is a bit wonky but it's the best I could come up with at 4 in the morn'. I have a table of links that I am paginating, nothing fancy. Let's say there are 100 links that are displayed 20 a page for 5 pages. How can I number each link starting with 1 and ending with 20 on the first page and if we skipped to the last page would be 81 through 100. I have multiple queries changing the direction and ORDER BY of my queries so this would have to be dynamically. Done using CakePHP 1.2. An example of this would be reddit.com

Try this in the view:

<?php debug($this->params['paging']); ?>

This'll give you a bit of inside information about the current status of the paginator. For example, you'll find this:

Array (
    [Model] => Array (
            [page] => 2
            ...
            [options] => Array (
                    [limit] => 20
                    ...

'limit' being the "items per page" and 'page' being, well, the page.
With this information it should be pretty trivial to insert this kind of counter into your output.

$page = $this->params['paging']['Model']['page'];
$limit = $this->params['paging']['Model']['options']['limit'];

$counter = ($page * $limit) - $limit + 1;

foreach ($models as $model) {
    echo $counter;

    // normal $model output

    $counter++;
}

Pagination Logic is as follows:

SELECT count(*) FROM my_table WHERE ... ORDER BY ...;

First, you want to know how many records there are to be paginated.

Then, divide the total number of records by the number of records you want per page and 'ceiling' this number, otherwise the last few records won't get their own page.

Now you have the number of records and the number of pages.

Next, for whatever page you're on, you multiply the page number minus 1 by the number of records per page so you know from what record to start grabbing further records. This query will looks something like:

SELECT * FROM my_table WHERE ... ORDER BY ... LIMIT {records per page x (current page number - 1)}, {records per page}

The reason you minus 1, is because if you were on page 1 and were grabbing 20 records per page for example, then 1 x 20 = 20, and we want to start grabbing records from 0, not 20 for the first page. So you minus 1 before multiplying.

Then you simply display the records!

:D

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