Server side optimization - Database result cache

As we know, the database will use many resource and time to query the information of Image. If we want to save time, we could do optimization with cache the result. What I use is two functions, you could use other PHP cache library too. The code I use is version 1.13. !! Please note: because I don't open the comment function, so it may have problem with comment.

You could go to site http://henku.info to see the cache result.

1, Edit the functions-db.php under zp-core directory.

2, Search function query_single_row, change it to:

function query_single_row($sql)
{
if ($cache = get_cache($sql))
return $cache;

$result = query($sql);
if ($result) {
$singlerow = mysql_fetch_assoc($result);

store_cache($sql, $singlerow);
return $singlerow;
} else {
return false;
}
}

3, Search function query_full_array, change it to:

function query_full_array($sql)
{
if ($cache = get_cache($sql))
return $cache;

$result = query($sql);
if ($result) {
$allrows = array();
while ($row = mysql_fetch_assoc($result))
$allrows[] = $row;

store_cache($sql, $allrows);
return $allrows;
} else {
return false;
}
}

4, Last thing, add two functions in functions-db.php. You could change "cachedirectory" to your cache directory, and change $cache_time_out to the expire time you want. 30* 24 * 3600 is 30 days.

function store_cache($query, $result_cache)
{
if (preg_match("/^(insert|delete|update|replace)\s+/i",$query))
return;
if (stristr($query, "ORDER BY RAND"))
return;

$cache_file = 'cachedirectory/'. md5($query);
error_log (serialize($result_cache), 3, $cache_file);
}

function get_cache($query)
{
$cache_time_out = 30* 24 * 3600;

if (preg_match("/^(insert|delete|update|replace)\s+/i",$query))
return;
if (stristr($query, "ORDER BY RAND"))
return;

$cache_file = 'cachedirectory/'. md5($query);
if ( file_exists($cache_file) )
{
if ( (time() - filemtime($cache_file)) > $cache_time_out )
{
unlink($cache_file);
}
else
{
$result_cache = unserialize(file_get_contents($cache_file));
return $result_cache;
}
}
}

Comments

  • The normal albums and images data is cached. The other searches are not frequent enough to warrant caching.
Sign In or Register to comment.