:Ben Metcalfe Blog

MySQL database caching in PHP

I’ve been searching around for some mechanisms to perform database caching within a PHP/MySQL solution I am building.

There are a number of solutions around (in addition to the official one).

Most seem to store the cache as an XML file, but that seems to be a really inefficient way of doing things (you have to write the XML and then parse it back in each time — almost as lengthy has making the original SQL request instead).

But then I managed to find class_db.php.

Its light – just a single class.php file to include, and it fits into your code effortlessly. It also (seems to) store your data in a format similar that of a raw SQL dump, making it really quick to parse out into an array.

The sum total of the integration of the cache into my php script was as follows:

$result = mysql_query($sql);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){


$d = new db(0);//define the db the cache should use.
$d->dir = "/path/to/dbcache/"; //cache location.
$rows = $d->fetch($sql, 1800);//1800 = 5 mins (in secs) for caching
foreach ($rows as $row){

For more information check out class_db.php by Troy Wolf.