《PHP教程:php+Memcached實現簡單留言板功能示例》要點:
本文介紹了PHP教程:php+Memcached實現簡單留言板功能示例,希望對您有用。如果有疑問,可以聯系我們。
相關主題:memcache擴展 / 鍵值KeyValue存儲數據庫
本文實例講述了php+Memcached實現簡單留言板功能.分享給大家供大家參考,具體如下:PHP應用
MyPdo.phpPHP應用
<?php class MyPdo{ private $pdo; function __construct() { $this->pdo = $this->getPdo(); } /** * CreatePDO * * @return PDO */ public function getPdo() { $dbms='mysql'; $dbName='testdb'; $user='root'; $pwd='diligentyang'; $host='localhost'; $dsn="$dbms:host=$host;dbname=$dbName"; try{ $pdo=new PDO($dsn,$user,$pwd); }catch(Exception $e){ echo $e->getMessage().'<br>'; exit(); } $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo->exec("set names utf8"); return $pdo; } /** * Execute SQL * * @param string $sql Sql * @param string $mode Mode * * @return mixed */ function query($sql = "", $mode = "array") { $sql = trim($sql); if ($sql == "") { $this->showErrors("the mothe query neet at least one param!"); } $query = $this->pdo->query($sql); if (!$query) { $this->showErrors("the sql string is false"); } if (strpos(strtolower($sql), "select") ===false) { return $query; } switch ($mode) { case 'array' : $res = $query->fetchAll(PDO::FETCH_ASSOC); break; case 'object' : $res = $query->fetchObject(); break; case 'count': $res = $query->rowCount(); break; default: $this->showErrors("SQLERROR: please check your second param!"); } return $res; } /** * 提示錯誤 * * @param string $str 錯誤提示內容 */ public function showErrors($str) { echo "<h1>$str<h1/>"; exit(); } }
ShowMessage.phpPHP應用
<?php include("MyPdo.php"); //連接Memcached服務器 $m = new Memcached(); $m->addServer('127.0.0.1',11211); //獲取Memcached中的list $res = $m->get("list"); //如果沒有數據,則從數據庫中查出,并放入Memcached中,如果有數據則直接輸出 if(!$res){ $MyPdo = new MyPdo(); $res = $MyPdo->query("select * from message","array"); $m->set('list',$res,3600); } foreach($res as $val){ echo $val['title']."-------".$val['content']."<br>"; } ?> <a href="AddMessage.php" rel="external nofollow" >添加留言</a>
AddMessage.phpPHP應用
<form action="CheckAdd.php" method="post"> 標題:<input type="text" name="title"><br> 內容:<input type="text" name="content"><br> <input type="submit" value="提交"> </form>
CheckAdd.phpPHP應用
<?php include("MyPdo.php"); //連接Memcached服務器 $m = new Memcached(); $m->addServer('127.0.0.1',11211); $title = $_POST['title']; $content = $_POST['content']; $MyPdo = new MyPdo(); $res = $MyPdo->query("insert into message(title,content) values('$title','$content')"); if($res){//如果insert語句執行成功則清除Memcache中的緩存 $m->delete("list"); } header("location:ShowMessage.php");
運行結果如下所示:PHP應用
PHP應用
PHP應用
注:此例子只是簡單實現了,留言列表和添加留言功能,需要注意的是,如果對數據庫的數據有了添加或修改,需要清除緩存,然后重新緩存一下,已保證數據顯示同步.PHP應用
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP+MySQL留言板開發專題》、《php緩存技術總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP錯誤與異常處理方法總結》、《php面向對象程序設計入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》PHP應用
希望本文所述對大家PHP程序設計有所幫助.PHP應用
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/1803.html