Reputation: 541
So I can't get this to work.
I have the variable $page
which contains the current page, $total_pages
which contain the total amount of pages and $limit
which contains the max number of rows per page.
I have tried doing a lot of stuff but I just don't get it.
This is the latest thing I tried. It works for page 1 & 2 but then it just stops working
if ($page == 1) {
$count = 1;
} else {
$count = $page * $limit/2 + 1;
}
That code was above my while-loop which loops out the rows.
Upvotes: 0
Views: 1050
Reputation: 71384
Think through the simple math here.
If $page
is a value >= 1, than the first row on each page would be calculated as follows:
$first_row_num = (($page - 1) * $limit) + 1;
You should not need different logic branch for first page vs. other pages.
Also note that when dealing with page numbers, that you will need to use zero-based page numbers when querying the database. So you need to do something like this before querying the database.
$offset = ($page - 1) * $limit;
And in your LIMIT clause you would use:
... LIMIT $offset, $limit
So considering you need to calculate the offset before displaying results, you might actually do something like:
$offset = ($page - 1) * $limit;
// make DB query here
// now calculate first row number using $offset
$first_row_num = $offset + 1;
Upvotes: 1
Reputation: 4559
This is :
if ($page == 1) {
$count = 1;
} else {
$count = ($page - 1) * $limit + 1;
}
It is equal to what you tried for $page = 1 or 2, that's why it worked. This is even shorter and works whaterver the value of $page
:
$count = ($page - 1) * $limit + 1;
Upvotes: 1