Example of using Memcached with PHP and Mysql

Abhigyan Singh 12th Jul 2020

In this tutorial we will learn about implementation of memcached in php and mysql. I will just show you a simple example of using memcached with PHP and mysql. Memcached is a general-purpose in-memory, high-performance and distributed memory object caching system.

Memcached is very useful and important in web technology to make faster website. Using memcached, you can implement memcached in block wise code or your whole program. Memcached is implementing on your sql query to reduce the server RAM load.


I recommend using memcached very carefully because bad implementation of memcached results slows your query or stuck the whole program.


1. After fully finalize your query, you should implement memcached in your mysql query.

2. While defining the memcached  key be careful to use unique key for every chunk of your code.

Code Implementation:

Before using memcached in your code, You need to install and configure the memcached. For installation and configuration read this tutorial

How to install memcache with wamp and PHP 5.3

Now after installation, we need to make server connection for memcached. For memcached server connection.

/* ======== Memcached Server Connection ========= */
$memcache = new Memcached();
$memcache->addServer('localhost', 11211) or die ("Could not connect");
/* ======== Memcached Server Connection ========= */

Now same time make database connection

/*========== Database Connection Code Start Here ============ */

define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", ""); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME",""); // set database name

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

/*========= Database Connection Code End Here ============== */

Full code:


$query = "SELECT name FROM YOUR_TABLE";

TTL = 1000; //Second

$setKey = md5("discussdesk_".$query); //set the memcached key. should be unique
$getCacheDetail = $memcache-&gt;get($setKey); // Get the cached content based on the key

/* This block check if cached value is avaliable then serve the data from cache else database*/
if ($getCacheDetail) {
echo "data comes from cache";
$rec = mysql_query($query);
$assoc[]=$result; // Results storing in array
$memcache-&gt;set($setKey, $assoc, TTL);
echo "data comes from database";

foreach($assoc as $resultvalue)
echo $resultvalue['name'];


While setting memcached key value, it is necessary to use unique key.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk