How to paginate a database query in PHP — the no-frameworks way

OK, I admit! Every time I have to write similar code I get stuck rethinking it — every time … If I wasted 10 minutes thinking of it every time, and I did so for 100 times, then I’ve already wasted more than 2 working days in the last 12 years doing it! I guess it’s time to stop that loss!

So, the issue I’m talking about is when having a web page (or a web service, or a command line utility, or any other interface) that lists a set of records from a database, and then the user wants to retrieve the next set of records, this is called pagination. If I’m not explaining it clearly, feel free to look it up in Wikipedia.

So, how should pagination be handled in the server side? Here is the most recent way I did it … If you have a better suggestion, feel free to post your comment below. I’ll be using this from now, and update it as necessary:

The tricky part that wastes most of the time in the above code is line 12 .. that is, figuring out the formula for calculating the offset, or the number of records to skip from the query .. it’s a simple one, I know, but if you’re like me and get confused by the zero-one worlds … it could drag your mind for some time! So, I hope this would save you 10 minutes in your next coding adventure.

Published by Genedy

I'm the founder of BigProf Software. We're a tiny team of developers who create tools that make it easy (and affordable) for anyone to create connected business applications that work from any device with a browser.