I’ve got close to 30 or so photos on my site, and I’d like them to be displayed in sets of 10, with a “Previous” and “Next” link allowing progress backward or forward through the pictures. You’ve all seen it, but can you help me to do it?
You create a loop and select one picture each time. That’s an incredibly inefficent way to connect with your DB. You should let the database do the work for you and select all the rows you want at once.
SELECT (the_stuff_you_want) FROM (table) WHERE (field) BETWEEN (start) AND (end)
You’ll need to substitute the placeholders with the right ones for your situation.
You then loop over your returned result set for the output, but to initiate a DB transaction each time is wasteful.
–
You probably want to start with a ‘select count …’ to find out how many records you’re dealing with total. Divide by the number you want to display per page (to figure out how many pages you need) and then assign a ‘page number’ as a local page variable. You can calculate start and end by doing (page_number * number_per_page) and ((page_number+1) * number_per_page)
That way you can just have links on the page to ‘?page=2’ etc.
You know never to display a link for pages <0 or more than the total you calculated.
You may also want to adjust the numbers so that you don’t have ‘page=0’ but that’s a personal preference. If you want the first page to be ‘page=1’ you’ll need to adjust your calculations accordingly.
The only gotcha with that is if your DB changes content between page views (as you may miss a picture).
Thanks for the replies everyone… I’ve revised the code heavily, based on your suggestions and some from a friend of mine.
I’m happy to report that the code is now completely functional.