静态文件能够加快访问速度,减少服务器压力等等,但是,当你的文章数量很多事,也
是很占磁盘的,实现原理其实很简单,就是利用 php 的文件操作生成静态的 html 文件。
当然也可以利用 php 的 ob 操作完成,我这里为了达到当发布文章或者更新文章立即生
成静态页面效果只用了一般 php 文件操作。
php 页面静态化原理:
1.创建测试数据库 test,建立 user 表如下(自己插入几条测试数据库):
1. CREATE TABLE IF NOT EXISTS
`news`
(
2.
`id`
int
(
10
)
NOT NULL AUTO_INCREMENT
,
3.
`title`
varchar
(
128
)
DEFAULT NULL
,
4.
`content`
text
,
5.
`time`
int
(
10
)
DEFAULT NULL
,
6. PRIMARY KEY
(
`id`
)
7.
)
ENGINE
=
InnoDB
DEFAULT CHARSET
=
utf8 AUTO_INCREMENT
=
12
;
2.建立连接数据文件 conn.php
1.
<?
php
2.
$dsn
=
"mysql:host=localhost;dbname=test;"
;
3.
$user
=
"root"
;
4.
$password
=
""
;
5.
try
{
6.
$dbh
=
new
PDO
(
$dsn
,
$user
,
$password
);
7.
}
catch
(
PDOException
$e
){
8.
echo
"连接失败"
.
$e
->
getMessage
();
9.
}
10. ?>
3.显示新闻列表(news.php),注意,其连接为静态 html 连接,这时还没生成,当然
链接打不开:
1.
<meta
http-equiv
=
"content-type"
content
=
"text/html;charset=utf-8"
/>
2.
<a
href
=
"add.php"
>
添加文章
</a>
3. <hr>