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.
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:
sudo apt-get install memcached
sudo apt-get install php-memcacheAfter installation, enable the extension in php.ini by adding:
extension=memcache.soConnecting to the Memcache Server
In PHP code, establish a connection to the Memcache server with memcache_connect:
$memcache = memcache_connect('localhost', 11211); // connect to localhost on default port 11211Writing Data to Memcache
Store data as a key‑value pair using memcache_set:
$key = 'user:123'; // key
$value = '张三'; // value
$expire = 3600; // expiration time in seconds
memcache_set($memcache, $key, $value, 0, $expire);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:
$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);
}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:
memcache_delete($memcache, 'user:123'); // delete by keyMemcache also offers advanced features such as automatic compression, CAS operations, and incremental storage, which can be applied as needed to further improve system performance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
