PHP memcache in database query, reduce the number of connections to the database, reduce the pressure on the server!
/* * memcache Application Notes memory cache memory caching * How it works * server ports port 11211 * MemCached access key value pair key => value * 1. Intranet Visit * 2. Setting up a firewall */ //creating Memcache objects $mem = new memcache (); //Connecting Memcache server $host = ' localhost '; $ port = ' 11211 '; $mem->connect ($host, $port); //$mem->addserver ($host, $port); //$mem->addserver (' 192.168.10.254 ', 11211); //add a server's memory $dsn = ' Mysql:dbname=test;host=localhost '; $username = ' root '; $passwd = ' Root '; $options = array ( PDO::ATTR_AUTOCOMMIT=>true, pdo::attr_persistent=>true ) //Connection Database try{ //creating objects $pdo = new pdo ($ dsn, $username, $passwd, $options); //setting error using exception mode $pdo SetAttribute (pdo::attr_errmode, pdo::errmode_exception); } catch (pdoexception $e) { echo "Database connection failed:". $e->getmessage ( ); exit; } $statement = "Select * from users where id > ? and id < ? "; //Key Name MD5 () after encryption name more specification Prevent query statement information Disclosure $key = md5 ($statement); //direct from memory to data $data = $mem->get ($key); //determine if there is a $data, if not only need to connect to the database to get data! Data is fetched directly from memory, implementing caching. &nbsP; if (Empty ($data)) { try{ //to database management system, post-compilation wait no execution $pdostatement = $pdo->prepare ($statement); $pdostatement- >execute (Array (3,6)); //mode of setting results $pdostatement->setfetchmode (pdo::fetch_num); $data = $pdostatement->fetchall (PDO:: FETCH_ASSOC); //saved in cache $mem->set ($key, $data, memcache_compressed,10); echo ' first database query!<br/> '; }catch ( pdoexception $e) { echo ' cause of the error : '. $e->getmessage (); } } / /output in tabular format echo ' <table border= ' 1 " width=" 800 " align= "center" > '; foreach ($data as $ Value) { echo ' <tr> '; echo ' <td> '. $value [' id ']. ' </td> '; echo ' <td> '. $ value[' username ']. ' </td> '; echo ' <td> '. $ value[' password ']. ' </td> '; echo ' <td> '. $ value[' email ']. ' </td> '; echo ' </tr> '; } echo ' </table> '; //close connection $mem->close ();
This article is from the "Jin Sha Harbor" blog, please be sure to keep this source http://11410485.blog.51cto.com/11400485/1842668
PHP memcache Memory Cache database query application Gaulo PHP