本文实例讲述了php+memcached实现简单留言板功能。分享给大家供大家参考,具体如下:
mypdo.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?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
1
2
3
4
5
|
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?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程序设计有所帮助。