I have read numerous guides about Memcached, however, several things remain unclear to me:
1) I’ve seen many examples, looking more or less like this:
$sql = "SELECT `name` FROM `users` WHERE `id` = 1;";
$memcache->set(md5($sql), $sql, false, 60);
$memcache->get(md5($sql));
However, with my limited knowledge of Memcache, I see a serious flaw here: I can’t use the same method to store data with INSERT/UPDATE requests as, technically, it would result in a different hash
As a solution I figured I could use something like this: creating a class/function that would do the following:
class db {
function insert($sql, $ttl, $key) { // $key would be the name of the key I would manually generate for each query. To maintain uniqueness for each user where needed, could be user_id_keyname
$memcache->set($key, $sql, false, $ttl);
mysql_query($sql);
}
function sel($sql, $ttl, $key) {
if ($memcache->get($key)) then return $memcache->get($key);
else {
$memcache->set($key, $sql, false, $ttl);
return mysql_query($sql);
}
Could this be a proper approach to my problem? Would truly love to see any comments on the code.
}
}
Why do you want to cache results of an
INSERT/UPDATEquery? There’s nothing wrong to use the md5 hash of theSELECTquery because you don’t need any other information to uniquely identify the result set. You only want to cache results fromSELECTqueries so you don’t have to retrieve the data from the database all the time. When you update the data, you don’t want to loose it so you have to send the query to the database.There’s another problem in your examples. You don’t actually store any query results in the cache. You only store the SQL query which is useless.