Cache your data with memcache

If you know that the results of SQL queries are likely to be read more often than they are written, you should consider caching them. This would allow you to read the result from your cache rather than hitting the database every time, which in turn allows you to scale up to handle exponentially more users.

Memcache is one of various possible caching options, but it's a good choice because it's mature, fast, easy to use and free. To get started, you'll need to install memcache on your server and the PHP memcached extension – if you're on Linux, both of these will be in your package manager.

Once it's installed, you can connect to memcache in PHP using these two lines of code:

$m = new Memcached();
$m->addServer('localhost', 11211);

You can then start setting and getting values. Memcache is what's called a key/value store, so it's like storing variables except that those variables exist in memcache not in PHP, so the values persist once your script finishes running.

To set a key in memcache, use this:

$m->set("yourkey", "yourvalue");

To read a key in memcache, use this:


Like I said, you can set and get keys whenever you want - they still in memcache for as long as the server is running, or unless your memcache server runs out of storage space and has to clear them.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Use persistent connections >>

Previous chapter: Debug your code

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.