Add ($key, $value, $expiry);
$key: Unique identification, used to differentiate written data
$value: Data to write
$expiry: Expiration time, default is always valid
Purpose: Write data to Memcache
Get ($key)
$key: Get the corresponding data by $key at write time
Use: Get the data in Memcache
Replace ($key, $value, $expiry)
The method parameter is the same as the parameter of the Add method
The use is also clearly the replacement data
Delete ($key, $time = 0)
$key: Unique identification
$time: Delay Time
Purpose: Delete data stored in Memcache
Let's take a look at the specific usage:
Add ($key, $value, $expiry);
$key: Unique identification, used to differentiate written data
$value: Data to write
$expiry: Expiration time, default is always valid
Purpose: Write data to Memcache
Get ($key)
$key: Get the corresponding data by $key at write time
Use: Get the data in Memcache
Replace ($key, $value, $expiry)
The method parameter is the same as the parameter of the Add method
The use is also clearly the replacement data
Delete ($key, $time = 0)
$key: Unique identification
$time: Delay Time
Purpose: Delete data stored in Memcache
Let's take a look at the specific usage:
Code
Copy Code code as follows:
<?php
$m = new Memcache ();
$m->connect (' localhost ', 11211);
$data = ' content '; Data that needs to be cached
$m->add (' MyKey ', $data); Echo $m->get (' MyKey '); Output content
$m->replace (' MyKey ', ' data '); The replacement content is Dataecho $m->get (' MyKey ');//Output data
$m->delete (' MyKey '); Delete echo $m->get (' MyKey '); Output false because it has been deleted oh ...
?>
Is it simple? In practical applications, the result set of a database query is usually saved to the memcached
The next time you access it directly from the memcached, and no longer do database query operations, which can greatly reduce the burden of the database.
The value after the SQL statement MD5 () is typically used as the unique identifier key. Below is an example of using memcached to cache query result sets for a database
Code
Copy Code code as follows:
<?php
//Connection Memcache
$m = new Memcache ();
$m->connect (' localhost ', 11211);
//Connect the database I will not write.
$sql = ' SELECT * from users ';
$key = MD5 ($sql);//md5 SQL command as unique identifier for memcache
$rows = $m->get ($key);/////First memcache get Data
if (! $rows) {
//If $rows is false then there is no data, then write data
$res = mysql_query ($sql);
$rows = Array ();
while ($row = Mysql_fetch_array ($res)) {
$rows [] = $row;
}
$m->add ($key, $rows);
//Here to write the data obtained in the heavy database, you can set the cache time, the specific time set how much, according to their own needs.
}
Var_dump ($rows);//Print out data
//The first time you run the program, because you have not yet cached data, you will read the database once, and when you access the program again, you will be able to memcache it directly.
?>