Problem caching mysql results
Posted: Wed Jan 20, 2010 8:42 pm
Hi, I'm building a content management system and I want my query results to be cached to improve page load, so I attempted to make a cache at first without looking at any tutorials and I failed, now I read a few things and made a new one, except now the mysql_query is faster than loading from cache.
Here is my code, of course I took out my other functions in the class because they are unnecessary but the code is below.
Thank you, if you are one of those who reply and attempt to help me 
Code: Select all
From Query: 0.00079894065856934
From Cache: 0.0017709732055664Code: Select all
class Raen_Cache {
protected function writeCache($file, $access, $data) {
$handle = fopen($file, $access) or die ("Raen Error: Unable to access " . $file);
fputs($handle, serialize($data));
fclose($handle);
}
protected function readCache($file) {
if (file_exists($file)) {
return @unserialize(file_get_contents($file));
} else {
$ret = "Raen Error: Cache file does not exist " . $file;
return $ret;
}
}
}
class Raen_DB extends Raen_Cache {
public function executeQuery($query) {
if (preg_match("/^SELECT/",$query)) {
$queryKey = md5($query);
$present = time();
$cacheFile = "cache/" . $queryKey . ".txt";
if (file_exists($cacheFile)) {
$fType = 'w';
} else {
$fType = 'x';
}
if (!file_exists($cacheFile) || ($present - 3600) > filemtime($cacheFile)) {
$result = mysql_query($query) or die(mysql_error());
while ($fetchArray = mysql_fetch_array($result) ) {
$sqlArray[] = $fetchArray;
}
$this->writeCache($cacheFile, $fType, $sqlArray);
return $sqlArray;
} else {
$readCache = $this->readCache($cacheFile);
return $readCache;
}
} else {
$result = mysql_query($query) or die(mysql_error());
return $result;
}
}
}