PHP Paging with Caching
The majority of PHP paging script with contain a request to the database for a total row count. This is perfectly acceptable if you script needs an exact and accurate results count. However, most sites don’t need a dynamic count and the total results count represents an uneeded database request. On busier sites this effect can become quite limiting and will slow down you scripts.
As an example take a website that gets say 10 hit per second, withouit caching this represents 20 (10 hits on your database and 10 hits on your database to fecth the result set) hits per second to your database – on larger sites and larger result sets this effect is amplified. However, by simply caching the total number of rows returned you can cut the requests to your database in half.
Google uses a caching system on their results (albeit more more complicated) and they never retuirn the exact amount of results (the perforamnce hit on a site as big and busy as Google would be absolutely huge!). Instead they present results as: “results 20-40 of about 248,000″ – with figure of 248,000 coming from an estimated cache value.
To cache the number of results the script would simply store a count of the total number of records in a SESSION variable (assume the cached session value is called “totalResults”. You could also store the result as a COOKIE that expires in the future, to force an update the cached number of rows. Using sessions, the code is very simply:
if( !isset($_SESSION['totalResults']) ) {
//Code to query your database for a row count
} else {
//use the total record count directly from the session variable
$myPagerObj->pageSomeData($_SESSION['total_records'], $perPage, $curPage);
}
It would also be wirth doing some validation on the cached page value, for security. However, the latter would usually be done directly in you’re paging class.




Recent Comments