## Storing Data in our Cache

Let's dive into data storage. We are going to take an example to make things clearer - an online shop. We have a script called edit_product.php whose purpose is to save a product's data into our database. Each one of our products has the following information:

• id
• name
• description
• price

At some point in our edit_product.php code, we run an INSERT or UPDATE SQL query whose purpose is to write this product's data to our MySQL database. It could look just like this :

As I mentioned above, we want to store our data both in our MySQL database and Memcached server. Here is how we are going to proceed :

At this point, both our database and cache contain our product data.

## Retrieving Data from our Cache

In case our cache is unavailable, we want to fall back to MySQL.

Now let's retrieve our data. In the same example, let's say our online shop has a script called product.php that displays a specific product. Accessing the page product.php?id=12 will display the product whose identifier is 12.

At some point in our product.php code, we run a SELECT SQL query whose purpose is to retrieve a product's data from our MySQL database. It could look just like this :

As we said above, we want to retrieve our data from our Memcached server if possible, because it's faster than getting it from MySQL. But in case our cache server can't be reached, or if it simply doesn't store the data we need, we want to fall back to MySQL. Here is how we are going to proceed :

At this point, we have retrieved the data we needed. It was most likely done from our cache, but could be from MySQL if the cache was not filled or couldn't be accessed for some reason.

## Conclusion

We have seen how Memcached can be used to speed up your website and limit your database load. Our example above was based on PHP and MySQL because these techologies are widely deployed, but this principle is universal and works just the same with many other technologies : C/C++, Java, Python, Ruby, Perl, .Net, MySQL, Postgres, Erlang, Lua, Lisp, Cold Fusion, Ocaml and io are listed along with PHP on the official Memcached wiki.

As I briefly mentioned earlier, Memcached provides more features than the simple set and get methods we've seen above. Two useful additional features are increment/decrement updates, and the ability to set an expiration time to a specific stored data. Both are available in PHP, along with a few others, as you can see in the Memcache documentation.

Have fun implementing this on your websites, and enjoy the —free— performances improvement. Thank you so much for reading and please let me know if you have any questions in the comments below.