Memcahced open source distributed memory object caching system it helps you to speeding up the dynamic web applications by reducing database server load.This system is very helpful for high traffic media and blog related websites.

Database
Sample database demos table contains id, title and link.

CREATE TABLE demos
(
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(300), 
link VARCHAR(300), 
);

First User Request

First request goes to database server at the same time data object storing in Memcached server. 


Second User Request
Second user request data comes from Memcached object. 

index.php
Contains PHP code. 

<?php
include(‘db.php‘);
$memcache = new Memcache;
$memcache->connect(‘localhost‘, 11211) or die (“Could not connect“);

$key = md5(‘List sample Demos’); // Unique Words
$cache_result = array();
$cache_result = $memcache->get($key); // Memcached object 

if($cache_result)
{
// Second User Request
$demos_result=$cache_result;
}
else
{
// First User Request 
$v=mysql_query(“select * from demos order by id desc”);
while($row=mysql_fetch_array($v))
$demos_result[]=$row; // Results storing in array
$memcache->set($key, $demos_result, MEMCACHE_COMPRESSED1200); 
// 1200 Seconds
}

// Result 
foreach($demos_result as $row)
{
echo ‘<a href=.$row[‘link‘].>.$row[‘title‘].‘;
}

?>


db.php
You have to change hostname, username, password and database name.

<?php
$mysql_hostname = “localhost“;
$mysql_user = “username“;
$mysql_password = “password“;
$mysql_database = “database“;
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) 
or die(“Opps some thing went wrong“);
mysql_select_db($mysql_database, $bd) or die(“Opps some thing went wrong“);
?>
Advertisements