Home arrow MySQL arrow Page 4 - Take Some Load off MySQL with MemCached

PHP MemCache PECL Extension - MySQL

While the execution speed of your codebase can be a factor in the overall scalability of your application, more often than not, your database will become a bottleneck first. Modern web development environments can generally serve many page loads per second, and each of these pages will often make many requests to the database for fresh information. These pages may also be rendered by an easily expandable pool of web servers. While databases, including MySQL, are adequately designed to handle a significant number of queries, eventually, the load from all these requests can become too much to handle.

  1. Take Some Load off MySQL with MemCached
  2. A Solution - Caching
  3. Enter MemCached
  4. PHP MemCache PECL Extension
By: Chris Moyer
Rating: starstarstarstarstar / 6
July 29, 2008

print this article



Obviously, you are not going to want to interact with MemCached on a regular basis by using telnet and by typing out the protocol commands. Instead, client libraries are provided for nearly every popular web development language: PHP, Perl, Ruby, Python, Java, and more. Here, we’ll focus on the PHP client.

The MemCache extension is a PECL module and may need to be installed separately from your PHP installation. In most cases, the PECL module can be installed and MemCache can be enabled without rebuilding or installing a new version of PHP. You can verify that the installation was successful by viewing the output of phpinfo(). You’ll get a section of the output with the MemCache status, number of active connections, and PECL extension version:

memcache support


Active persistent connections



$Revision: 1.80 $

Once you’ve verified the installation, you can start using your cache! Here’s an obligatory “Hello, World!” using MemCache.

$memcache = new Memcache;

$memcache->connect(‘localhost’, 11211) or die(‘Memcache Connection Failed’);

$memcache->set(‘mykey’, ‘Hello, World!’);

$myvar = $memcache->get(‘mykey’);

print $myvar; // Outputs: Hello, World!

Using our news headlines example from before, here’s a better example:

// Obtain an array of news headlines

// Each healine is an array or headline, link and img

function fetchHeadlines($category_id) {

// Load cached headlines

$memcache = getMemcache(); // wraps creation and connection of

// MemCache object

$articles = $memcache->get(‘articles:’ . $category_id);

if ($articles) {

// cache hasn’t expired

return $articles;


// The cache doesn’t exist (probably expired)

// Load articles from the database

$dbh = getMysql(); // Wraps MySQL server connection

$result = mysql_query(‘SELECT * FROM news WHERE category_id=”’ . mysql_escape_string($category_id) . ‘” AND status=1 ORDER BY publish_date DESC LIMIT 5’, $dbh);

// Build an array of articles

$articles = array();

while ($article = mysql_fetch_assoc($result)) {

$articles[] = $article;


// Store back into the cache

$memcache->set(‘articles:’ . $category_id,



60 * 15); // Store for 15 minutes

return $articles;


In this example, we see a couple different things. The value of data used with the PHP library can be nearly any PHP variable. The data is converted into a string with the serialize() function, so numbers, strings, arrays, and most objects will be stored easily… only resources (file descriptors, database connections, MemCache connections) can not be stored effectively. Additionally, we see using the key as an example of an arbitrary lookup table: an ad-hoc string with the keyword ‘articles:’ and the category id from a simple, but effective key.

At this point, if you’re site is loaded one time per second, you’ve decreased the number of queries for the news table from 900 every fifteen minutes to one every fifteen minutes. That's not bad for a handful of code. And even if your site traffic increases from one hit per second to 100, you’ll still only be querying the news table once every fifteen minutes.

It is important to keep in mind that if the MemCached server crashes or the process dies, all your cache data will be lost. Always store the actual data in a database server or another persistent storage system.


While the example we created is fairly trivial, it’s easy to see how this technique can be expanded throughout your site. Other queries and other data can be cached with similar benefits. Obviously, MemCached isn’t the only solution to web scaling and data caching, but it can be a pretty useful. Often, as seen in our example, a MemCached solution can be implemented and put in place with minimal code changes, minimal time, and, hopefully, minimum downtime for your users!

>>> More MySQL Articles          >>> More By Chris Moyer

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Oracle Unveils MySQL 5.6
- MySQL Vulnerabilities Threaten Databases
- MySQL Cloud Options Expand with Google Cloud...
- MySQL 5.6 Prepped to Handle Demanding Web Use
- ScaleBase Service Virtualizes MySQL Databases
- Oracle Unveils MySQL Conversion Tools
- Akiban Opens Database Software for MySQL Use...
- Oracle Fixes MySQL Bug
- MySQL Databases Vulnerable to Password Hack
- MySQL: Overview of the ALTER TABLE Statement
- MySQL: How to Use the GRANT Statement
- MySQL: Creating, Listing, and Removing Datab...
- MySQL: Create, Show, and Describe Database T...
- MySQL Data and Table Types
- McAfee Releases Audit Plugin for MySQL Users

Developer Shed Affiliates


Dev Shed Tutorial Topics: