Home > Backend Development > PHP Tutorial > php uses MemCache to query the database

php uses MemCache to query the database

WBOY
Release: 2016-07-29 09:14:30
Original
1037 people have browsed it

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template