Home >Backend Development >PHP Tutorial >php uses MemCache to query the database
header("Content-type:text/html;charset=utf-8");
/**
* Used to execute sql statements of all result sets and cache the result sets into the memcached server
*@param
string $sql
Query statement SQL with result set
* @param object
$memcache object of class Memcache
*@return $date
Return the data of the result set
*/
function select($sql,Memcache $memcache) {
/* md5 sql command as the unique identifier of memcache*/
$key=md5($sql);
/* First get the data from the memcached server*/
$data=$ memcache->get($key);
/* If there is no data, get it from the database*/
if(!$data){
try{
$pdo=new PDO( "mysql:host=localhost;dbname=test","root","root");
}catch(PDOException $e){
die("Connection failed:".$e-> ;getMessage());
}
$pdo->query("set names utf8");//Prevent garbled characters
$stmt=$pdo->prepare($sql);
$stmt->execute();
$data=$stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($data);//Test
$memcache ->add($key,$data,MEMCACHE_COMPRESSED,0);
}
return $data;
}
$mem=new Memcache;
$mem->connect( "localhost","11211");
$data=select("select * from book",$mem);
//echo "
";<br><span></span>print_r($data); <br><span></span>//echo "";
The above introduces how PHP uses MemCache to query the database, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.