Use your left/right keys to browse tutorials
Using Memcache With PHP

Using Memcache With PHP

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on November 6, 2009

I want to just start this little post with that fact that I don’t know all the ins and outs of using Memcache but I have enough knowledge to just about get it working. I have access to a Mediatemple Dedicated Virtual Extreme server and managed to install it on the server using SSH, with the help of this little guide from Mediatemple which runs you through the installation process step by step.

Who uses Memcache?

Memcache was developed by Danga Interactive to enhance the speed of, Memcache dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a Memcache miss. Currently FaceBook are the biggest users of Memcache. Infact FaceBook are using it so aggressively that they are chartering new territory, and helping to develop the open source project.


What’s Memcached?

So your reading this wondering what I’m talking about. Memcache is basically is a generalpurpose distributed memory caching system, put that in English, it allows you to store any form of data in a ‘temporary cache’ so wherever you go to do a database query, instead of just connecting to the database and getting the data we want we first check the memcache to see if our data is already stored. If the memcache returns nothing, then go to the database, get what you’re looking for, then store it in the memcache for later:

There are five main functions that we use with Memcache and they are as follows:

  • get() – gets the value for a specified key
  • set() – sets a given key with a given value
  • add() – adds to the cache, only if it doesn’t already exist
  • replace() – sets in the cache only if the key already exists
  • flush() – removes all keys and cached data


The Code

So once you have Memcache installed on your server you can connect to it and start caching stuff. It’s worth pointing out that you shouldn’t go out and cache everything, it’s really only useful when you have large amounts of data that are going to be requested regularly.

  1. So the first two lines setup the connection to Memcache.
  2. The include is just my database connection script.
  3. Next we set the key. When we store data using Memcache there are 3 parts to storing the data, those three parts are the key, the value, and the expiry time of the cached item. The key is used to reference the stored data. in this example you can see that the key is an MD5 hash of the database query.
  4. we then check if the key exists in the cache. this will return true or false. if the data is found in the cache then we can access it.
  5. If the data isn’t found in the cache we connect to the database to get it. we store the data in the cache by using the follow line: $memcache->set($key, $row, TRUE, 20); $row refers to the array that we get from the database, notice the 20 at the end. This refers to the how long this item will expire in the cache. It is measured in seconds.

$memcache = new Memcached();
$memcache>connect('', 11211) or die ("Could not connect");


//set the key then check the cache
$key = md5("SELECT * FROM memcached_test where name='ashley'");
$get_result = $memcache>get($key);
if ($get_result) {
echo $get_result['name'];
echo $get_result['username'];
echo "Data Pulled From Cache";
else {
 // Run the query and get the data from the database then cache it
 $query="SELECT * FROM memcached_test where name='ashley';";
 $result = mysql_query($query);
 $row = mysql_fetch_array($result);
 $memcache>set($key, $row, TRUE, 20); // Store the result of the query for 20 seconds
 echo "Data Pulled from the Database";

This is a very simple example of how to use memcache, but I hope it has been an insight into how caching works.

More tutorials from Papermashup
29 discussions around Using Memcache With PHP
Older Comments
  1. says:

    Yes! Finally something about site link.

  2. prabha says:

    Always data retrieve from mysql da… how to retrieve data from memcache and how to know… pls any help me

  3. Jam says:

    Hello Ashley,

    Is the script still valid with jQuery 1.8 ?



  4. StudyHills says:

    Short and crispy, good work man.

  5. Umar says:

    Really a great post about the memcache concept ever.

  6. Umar says:

    Really a Great post for the memcache concept ever.

  7. Great post. I have learned many thing from here. thanks for your kind sharing.

Older Comments

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.

What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.