Memcache Example


<?php
ini_set('display_errors',1);
$memc = new Memcache;
$memc->addServer('localhost','11211');

if(empty($_POST['film'])) {
?>
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>Simple Memcache Lookup</title>
    </head>
    <body>
      <form method="post">
        <p><b>Film</b>: <input type="text" size="20" name="film"></p>
        <input type="submit">
      </form>
      <hr/>
<?php

} else {
  
    echo "Loading data...\n";
  
    $film   = $_POST['film'];
    $mfilms = $memc->get($film);

    if ($mfilms) {

        echo "<p>Data for  loaded from memcache</p>";

        print_r($mfilms);

    } else {

        $mysqli = mysqli_connect('localhost','root','root','test');
  
        if (mysqli_connect_error()) {
            sprintf("Database error: (%d) %s", mysqli_connect_errno(), mysqli_connect_error());
            exit;
        }
  
        $sql = sprintf('SELECT * FROM user WHERE name="%s"', $mysqli->real_escape_string($film));

        $result = $mysqli->query($sql);

        if (!$result) {
            sprintf("Database error: (%d) %s", $mysqli->errno, $mysqli->error);
            exit;
        }

        $row = $result->fetch_assoc();

        $memc->set($row['name'], $row);

	echo "Data loaded From database";
        print_r($row);
    }
}
?>
  </body>
</html>

Table data :

INSERT INTO `user` (`id`, `name`) VALUES
(1, ‘prasshant’),
(2, ‘testsss’),
(3, ‘hemu’),
(4, ‘gaurav’);

Reference: https://dev.mysql.com/doc/refman/5.6/en/ha-memcached-interfaces-php.html

Installation

Install memcached server in local if you do not have it live or third party

>sudo apt-get install memcached

The host and port will be localhost and 11211

Install memcache Client

> sudo pecl install memcache

if it gives phpize error then you need to install php-dev

> apt-get install php5.6-dev (or change the version according to your php version)