Backend Development 4 min read

Using Memcache in PHP for Efficient Data Storage and Retrieval

This guide explains how to install, configure, and use Memcache in PHP for fast data storage, retrieval, and deletion, including connection setup, key‑value operations, cache miss handling, and optional advanced features to boost backend performance.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using Memcache in PHP for Efficient Data Storage and Retrieval

Memcache is a high‑performance distributed memory object caching system that can cache database query results, page fragments, session data, etc., improving data access speed by storing data in memory.

Installation and Configuration of the Memcache Extension

First install the Memcache extension using the following commands:

<code>sudo apt-get install memcached
sudo apt-get install php-memcache</code>

After installation, enable the extension in php.ini by adding:

<code>extension=memcache.so</code>

Connecting to the Memcache Server

In PHP code, establish a connection to the Memcache server with memcache_connect :

<code>$memcache = memcache_connect('localhost', 11211); // connect to localhost on default port 11211</code>

Writing Data to Memcache

Store data as a key‑value pair using memcache_set :

<code>$key = 'user:123'; // key
$value = '张三';   // value
$expire = 3600;    // expiration time in seconds

memcache_set($memcache, $key, $value, 0, $expire);</code>

The above code sets the key user:123 to the value 张三 with a one‑hour expiration.

Retrieving Data

Retrieve data with memcache_get . If the key is missing, fetch from the database and cache it:

<code>$user = memcache_get($memcache, 'user:123'); // query by key

if ($user === false) { // data not found
    // read from database and cache
    $user = getUserFromDB(123);
    memcache_set($memcache, 'user:123', $user, 0, $expire);
}</code>

This logic first attempts to get the value from Memcache; on a miss it falls back to the database and stores the result in Memcache for future requests, reducing database load.

Deleting Data

Remove cached data with memcache_delete :

<code>memcache_delete($memcache, 'user:123'); // delete by key</code>

Memcache also offers advanced features such as automatic compression, CAS operations, and incremental storage, which can be applied as needed to further improve system performance.

cachingmemcache
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.