Reputation: 3921
I have a database in mysql and i want to fetch data from mysql at the first time and store it in memcache.
Second time i want to fetch it from memcahce and displaying it from memcache for 2-3 minute then again from database. I am very new to memcache and expecting small example so that i can understand.
Upvotes: 2
Views: 1088
Reputation: 3921
For starting with Memcache , make a simple database and insert some value in it. I am giving you the php file named it whatever you want sample_memcache.php
Note : $dbhost, $dbuser, $dbpass, $dbname is your localhost, your database username, password and database name respectively.
<html>
<head>
</head>
<body>
<form method="post">
<p><b>Name</b>: <input type="text" size="20" name="name" /></p>
<input type="submit" value="Submit" />
</form>
<?php
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect");
mysql_select_db($dbname);
$id = $_REQUEST['name'];
//echo $id;
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$key = md5("SELECT * FROM memc where FirstName='{$id}'");
//echo $key;
$get_result = array();
$get_result = $memcache->get($key);
if ($get_result) {
echo "<pre>\n";
echo "FirstName: " . $get_result['FirstName'] . "\n";
echo "LastName: " . $get_result['LastName'] . "\n";
echo "Age: " . $get_result['Age'] . "\n";
echo "Retrieved From Cache\n";
echo "</pre>\n";
} else {
// Run the query and get the data from the database then cache it
//echo $id;
$query="SELECT * FROM memc where FirstName='{$id}'";
//echo $query;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo "<pre>\n";
echo "FirstName: " . $row[1] . "\n";
echo "LastName: " . $row[2] . "\n";
echo "Age: " . $row[3] . "\n";
echo "Retrieved from the Database\n";
echo "</pre>\n";
$memcache->set($key, $row, MEMCACHE_COMPRESSED, 60); // Store the result of the query for 20 seconds
mysql_free_result($result);
}
?>
</body>
</html>
Upvotes: 2
Reputation: 7981
This is basic memcache usage. Essentially what you need to do is, before retrieving a value from the database, check whether it exists already in memcache. If it does, use that value. If not, retrieve it from the database and store it in memcache with a suitable expiry time. Generally this works by creating a wrapper of some sort that you use to retrieve data.
Unless you have a more specific question, I'd suggest you start with the Memcached introduction. The PHP documentation also has several examples that can get you started.
Upvotes: 1