In this tutorial you’ll learn about memcached server integration with php to Improve your php based application performance, Few days back i have posted tutorial about NodeJs with Memcached tutorial for beginner , Now i’ll tell how to do same thing with the php.

If you are working on any big database application, Then you might have faced problem with site performance, If your database have 10 lakh+ entry and trying to integrate search feature on website using PHP+MYSQL then your mysql query performance seems to be slow.

You can store your mysql most callable data in memcached server in key pair format, It stores data in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.

First of all install memcached server with php+memecached connectivity plugin in your ubuntu machine

sudo apt-get install memcached php5-memcache

Write below code to make connection with memcached server using php

<?php
$mem = new Memcached();
$mem->addServer('localhost', 11211);
?>

Where 11211 is memcached default port number.

Now create your first key in memcached server

//$mem->set('key','value');
$mem->set('name','Rohit');

You can also store array value in memcached key, Below is the simple static array, You can fetch data from mysql server and store in memecached key.

$profile = array('name'=>'Rohit', 'location'=>'Kanpur', 'emailid'=>'[email protected]');
//$mem->set('key','value');
$mem->set('profile',$profile);



Use below line of code to fetch your saved key from memcached

var_dump($mem->get('name'));
var_dump($mem->get('profile'));

php-memcached

If you want completely delete stored key from memcached, Use below line of code.

//$mem->delete('Key_Name');
$mem->delete('name');
$mem->delete('profile');

Final file will be..

<?php
$mem = new Memcached();
$mem->addServer('127.0.0.1', 11211);
 
$mem->set('name','Rohit');
 
$profile = array('name'=>'Rohit', 'location'=>'Kanpur', 'emailid'=>'[email protected]');
//$mem->set('key','value');
$mem->set('profile',$profile);
 
echo "<pre>";
echo "<br/>Single Key:-<br/>";
var_dump($mem->get('name'));
echo "<br/>Array Key:-<br/>";
var_dump($mem->get('profile'));
?>

These are the very basic set, get and delete command of memcached in php, You can follow below url to read full memcached commands.
http://php.net/manual/en/book.memcached.php

If you like this post please don’t forget to subscribe my public notebook for more useful stuff.