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.

Published by

Rob Allport

Web Developer based in Stoke-on-Trent Staffordshire Google+ - Twitter

One thought on “PHP Paging with Caching”

  1. Hello,

    I found your blog from the web designers forum – i see you post quite a lot there 🙂

    I just have one comment to make re your article. While sessions are a very quick way to achieve what you want you should really be using a proper caching framework such as APC – or alternative php cache. It’s quite easy to you simply set and retreve values from the cache using built in functions like apc_add and apc_fetch. More importantly you can also clear whole or part of the cache using apc_delete – you could run this in your destroy method in your classes for eg.

    web guru

Leave a Reply

Your email address will not be published. Required fields are marked *