PHP Caching using Memcached

January 24, 2008 | In: Caching, PHP

Why cached? It’s simple, you want speed. How? Say you have search application on your php webapp that yields thousands of results. Of course these are divided in a nice paginated links. Without caching, everytime the user jumps from each paged result links, your app will query your database, which adds overhead.

By using caching, you’re storing the result set in a temporary container(in case of memcached, it’s the memory) so that only one call to the DB is done.

Here’s the logic.

1. First check if we have cached the result set coming from DB.

2. If not, run the query.

3. Now, save the result set into cache.

4. If yes(see #2), get the result set from the cache.

Why Memcached? Well IMHO, it’s fast and it’s supported by php using libmemcache. You can see the complete details and can download it from

Can you provide sample snippet? See below.

connect($memcache_host, 11211);

// now let's check for cached data
if(!$memcache_obj->get('unique_key')) {
     // your very large query here and assign the result in $resultset
     // save the db result into the cache, set the cache lifetime for 5 minutes(60 sec * 5)
     $memcache_obj->set('unique_key', $resultset, MEMCACHE_COMPRESSED, 300);
} else {
     $resultset = $memcache_obj->get('unique_key');

// do useful things with the $resultset


It’s so simple , yet so helpful.

3 Responses to PHP Caching using Memcached



November 5th, 2008 at 8:06 am

Explained in very simple way. Its great.

But i am getting problem in saving resultset in memcache.

I am saving resultset in memcache and then doing print_r, it is displaying O:13:”mysqli_result”:0:{}

And not treating it as mysqli_result.

So how we can save it as mysqli_result in memcache?



November 30th, 2008 at 8:35 am

Hi Dheeraj,

Sorry for the late reply, please check first the output of your mysqli_result, print_r it to verifiy that you get what you need to get, before saving it to memcached. Maybe the result is empty so the memcached also saved an empty result set.

Hope that helps


Memcached installation on Linux» FROST : FRee and Open Source Technologies

September 22nd, 2009 at 10:58 pm

[…] my previous post about speeding up your application using memcached, i discussed the actual usage of memcached, but before we use it, we need to install it first, so […]

Comment Form