[thelist] PHP Previous Next Navigation

Simon Willison simon at incutio.com
Mon Jun 3 14:13:01 CDT 2002


At 12:05 03/06/02 -0500, Jay Blanchard wrote:
>Good afternoon!
>
>I am working on a project where approximately 3k - 5k records are returned
>and need to be displayed 30 per page with 'previous' and 'next' navigation
>at the request of the users. Does anyone know of an efficient script that
>will do this in PHP (with MySQL) that will not query the database every
>time? I would like to place the records into an array after one query to the
>database and then navigate the array.

I'm pretty sure it would be more efficient to query the database on each
page load rather than create and store an array of 3,000 items pesistently
across page views :)

MySQL has a very useful syntax when doing a next/prev button - the "LIMIT
X,Y" command (e.g "select * from news limit 0, 10")

X = The first item to display (10 would mean "start at the 10th item in the
list")
Y = how many to display after that first item (20 would mean "return 20 items")

To create the next/previous buttons You need to know how many records have
been returned and what "page" you are on. If no page is set (or page = 1)
perform "select ... limit 0, 10". If a page has been specified (e.g page 3
of the results) do $x = 10 * page (i.e 30) then "select ... limit $x, 10) -
obviously you should change 10 to reflect the number of results you want to
display.

Finally, to create your next/prev buttons first check if there are any
results left to show (see if the total number of results for your query is
less than $page * 10) - that tells you if a £next" button is needed. Then
check if you are on the first page or not, and if not display a "previous"
button.

Hope that explanation is clear enough,

Simon




More information about the thelist mailing list