I have been trying to add pagination to the above code. I cannot seem to get the pagination to work. Could someone please give me a tutorial on this or some code to try on my recordsets
PHPJavaScriptMySQL Server
Last Comment
doctorbill
8/22/2022 - Mon
Olaf Doschke
Pagination in MySQL is simple, look at the LIMIT and OFFSET clause.
10 records per page?
LIMIT recordsperpage
Nth page instead of first page?
OFFSET (pageno-1)*recordsperpage
That's it, mostly. Your records will only be for that page. You only need to specify the recordsperpage and pageno numbers.
As Olaf alluded to, the key to pagination is passing in a LIMIT clause to your SELECT query:
SELECT * FROM yourTable LIMIT startRow, NumberOfRows
Now the Number of Rows is likely to remain static throughout your applications - each page will need to show the same number of records, for example 10. The dynamic part is the starting row (or Offset), which is created by multiplying the page number you want with the number of records per page. For example:
You'll need to do some additional maths because the records are numbered using zero as a base, so page 1 needs to start at record 0, page 2 needs to start at 10 for example. This is easy to do by subtracting 1 from the page passed it
To build your pagination links in the first place, you'll need to retrieve the total number of records in your query and divide that by the number of records per page. We use the ceil() function to round up the fractions. Something along these lines:
Is there anything in my example that doesn't make sense. It's up to you to implement it into your own code - just copying and pasting a solution won't really help you in the long run as you won't understand what your own code is doing.
I have got the pages working using manual url's:
?page=1
?page=2
etc
This works fine on my recordset and the results are 1-10 records on page1, 11-20 on page 2 etc
I am just having a problem with this part:
$numberOfPages = ceil($totalRecords / $recordsPerPage);
for ($i=1; $i <= $numberOfPages; $i++) {
printf('<p><a href="?page=%1$s">Page %1$s</a></p>', $i);
}
This is just printed as text in the page. How do I define these variables
Chris Stanyon
Hey Bill,
What do you mean - printed as text in the page. That code will work out how many pages you need and then echo out a link for each one, something like this:
10 records per page?
LIMIT recordsperpage
Nth page instead of first page?
OFFSET (pageno-1)*recordsperpage
That's it, mostly. Your records will only be for that page. You only need to specify the recordsperpage and pageno numbers.