Monday 8 April 2013

How to use memcache with php


Previously I posted an article on how to install Memcache. This time I will show how to use Memcache with PHP. This program will start off with a SQL query statement, hashing the statement and check if the data is stored in memcache.If found, the data will be retrieve from memcache. If it is not found in memcache, then it will query from MySQL database.


<?php
require('connect_db.php'); 
$memcache_host="127.0.0.1";
$memcache_port="11211";
$memcache = new Memcache;
$memcache->connect($memcache_host,$memcache_port) or die ("Cannot connect");

$version = $memcache->getVersion();
echo "Version: ".$version;

$query="select * from exampleDB limit 1;";
$key = md5($query); 
$get_result = $memcache->get($key);

if ($get_result) {   
    print_r($get_result);
    echo "Data retrieved from memcache";
}
else {    
    $result = mysql_query($query);
    if (!$result) {
        die('Invalid query: ' . mysql_error()) 
      }
    $row = mysql_fetch_array($result);
    print_r($row);  
    $memcache->set($key, $row, MEMCACHE_COMPRESSED, 10); 
    echo "Data retrieved from database";
}  
?>

No comments :

Post a Comment

search iomeweekly