本文实例讲述了php+memcached实现简单留言板功能。分享给大家供大家参考,具体如下:
mypdo.php
<?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.php
<?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.php
<form action="checkadd.php" method="post"> 标题:<input type="text" name="title"><br> 内容:<input type="text" name="content"><br> <input type="submit" value="提交"> </form>
checkadd.php
<?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+mysql留言板开发专题》、《php缓存技术总结》、《php数组(array)操作技巧大全》、《php字符串(string)用法总结》、《php错误与异常处理方法总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!