The problem:

What I wanted to do here was find a way of speeding up a query that was run on MySQL database on a different server. Also I’m a big fan of caching generally, especially when the data is only updated once or twice a day.

When I was running the queries directly off the remote server it was noticably slow but with this solution in place things are flying!

Whilst there are ways of caching MySQL queries using MySQL this would be pretty pointless for a remote query, the only solution was to cache the results locally.

The solution:

class_db.php by Troy Wolf

What this class does is provide an layer between your query and database server (it supports several DBs) which runs the query and then writes the results to a file in a serialized format. E.g.

a:10:{i:0;a:8:{s:13:”Dunster House”;s:10:”short_desc”;s:157:”A warm welcome to Dunster House. We are a friendly family run Guest House situated within walking distance of Torquay’s main attractions. Beds from £20″;s:4:”town”;s:7:”Torquay”;s:3:”lat”;N;s:3:”lon”;N;}….

In the class you need to hard code the details of your DB connection(s) and set up your cache directory. Then it’s as straightforward as:

include("class_db.php");

$d = new db(0); //use first connection info from class_db

$sql = "SELECT `id`
 FROM accommodation
 WHERE `type` = ".$catNo;
$q_name = 'num_'.md5($catNo;);
$rows = $d->fetch($sql, 3600, $q_name);//run query, cache for 1hr, save cahce file as $q_name

foreach($rows as $row){
...
}

Easy as that. You have now run the query on the remote server and created a cached local result which will be called until it expires.

For an example of the script in action: http://www.devon-stay.com/Ilfracombe/camping.htm

http://www.devon-stay.com/Ilfracombe/camping.htm