CakePHP: Numbered Resultant Results

The title is a little awkward, but it's the best I could think of at 4am. I have a table of links that I paginate, nothing fancy. Let's say there are 100 links that display 20 pages to 5 pages. How can I number each link from 1 to 20 on the first page and if we skip the last page it will be 81 to 100. I have multiple queries changing the direction and ORDER BY of my queries so this should be dynamic ... Made using CakePHP 1.2. An example of this would be reddit.com

+2


source to share


2 answers


Try this in a view:

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

      

This will give you some information about the current status of the paginator. For example, you will find the following:



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

      

'limit'

- these are "elements on the page" and 'page'

, namely the page.
With this information, it should be pretty trivial to insert this 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++;
}

      

+5


source


The pagination logic looks like this:

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

First, you want to know how many posts should be paginated.

Then divide the total number of posts by the number of posts you want on the page and the ceiling for that number, otherwise the last few posts won't get their own page.

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



Next, for whatever page you are on, you multiply the page number minus 1 by the number of records per page to find out which record to start grabbing further records from. This request will look something like this:

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

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

Then you just show the entries!

: D

-1


source







All Articles