Memcache tips in PHP

  • 2020-03-31 20:20:59
  • OfStack

Add ($key, $value, $expiry);
$key: unique identifier used to distinguish written data
$value: the data to write
$expiry: the expiry time shall be deemed to be valid for ever by default
Purpose: write data to memcache

Get ($key)
$key: get the corresponding data by writing $key
Purpose: get data from memcache

The replace ($key, $value, $expiry)
This method parameter is the same as that of the add method
The obvious use is to replace data

Delete ($key, $time = 0)
$key: unique identifier
$time: delay time
Purpose: delete data stored in memcache

Here's how:
Add ($key, $value, $expiry);
$key: unique identifier used to distinguish written data
$value: the data to write
$expiry: the expiry time shall be deemed to be valid for ever by default
Purpose: write data to memcache

Get ($key)
$key: get the corresponding data by writing $key
Purpose: get data from memcache

The replace ($key, $value, $expiry)
This method parameter is the same as that of the add method
The obvious use is to replace data

Delete ($key, $time = 0)
$key: unique identifier
$time: delay time
Purpose: delete data stored in memcache

Here's how:

code
 
<?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 the content
$m->replace('mykey', 'data'); // Replace the content as dataecho $m->get('mykey');// The output  data 
$m->delete('mykey'); // delete echo $m->get('mykey'); // The output  false  Because it's been deleted .. 
?> 



Isn't it simple.. In practice, it is common to store the result set of a database query in memcached
Getting it directly from memcached on your next visit, rather than doing database queries, can greatly reduce the burden on the database.
The value after the SQL statement md5() is typically used as the unique identifier key. The following is an example of using memcached to cache the result set of a database query
code
 
<?php 
//Connect memcache
$m = new Memcache(); 
$m->connect('localhost', 11211); 
//I'm not going to write the database connection.
$sql = 'SELECT * FROM users'; 
$key = md5($sql); //The md5 SQL command ACTS as a unique identifier for memcache
$rows = $m->get($key); //First retrieve the data from memcache
if (!$rows) { 
//If $rows is false then there is no data, so write the data
$res = mysql_query($sql); 
$rows = array(); 
while ($row = mysql_fetch_array($res)) { 
$rows[] = $row; 
} 
$m->add($key, $rows); 
//Here write the data obtained in the heavy database, you can set the cache time, the specific time set how much, according to their own requirements.
} 
var_dump($rows); //Print out data
//The first time you run the program above, the database is read once because there is no cached data, and when you access the program again, it is retrieved directly from memcache.
?> 

Related articles: