用PHP制作简单的留言板
1、我们先把表单的代码写出来:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>留言板</title>
<link rel="stylesheet" type="text/css" href="./css/test27.css" />
</head>
<body>
<span>留言板</span>
<div>
<form action="test27-1.php" method="post">
<textarea name="contern">
</textarea><br />
留言用户:<input type="text" name="user"/><br />
<input type="submit" value="留言"/>
</form>
</div>
我们这里把表单放到一个<div>里面。
2、接下来,创建mysql数据表,表的名称为liuyan:

3、接下来,我们用另一个<div>来存放PHP从MySQL数据库中查询出来的结果,代码接着上面的。
<div id="show">
<?php
$cc=mysqli_connect("localhost","root",""); //连接MySQL数据库
$db=mysqli_select_db($cc,"test"); //选择数据库
$sql="select * from liuyan"; //查看liuyan表所有的数据
$re=mysqli_query($cc,$sql); //执行SQL语句
echo "<table border='1'>";
echo "<tr><th>留言用户</th><th>留言内容</th><th>留言时间</th></tr>";
while($r=mysqli_fetch_array($re,MYSQLI_BOTH)){ //循环输出数据
echo "<tr><td>".$r['name']."</td><td>".$r['content']."</td><td>".$r['time']."</td></tr>";
}
echo "</table>";
?>
</div>
</body>
</html>
4、接下来,我们书写CSS样式表,代码如下:
*{
margin:0;
padding:0;
}
span{
display:block; //以区块显示
text-align:center; //居中对齐
margin-top:20px; //向上挤外边20px
font-size:22px; //字体大小22px
font-weight:bold; //字体加粗
margin-bottom:15px; //向下挤下边15px
}
div{
width:300px;
height:80px;
margin:0 auto;
font-weight:bold;
}
textarea{
width:300px; //宽300px
height:80px; //高80px
background:#eee;
margin-bottom:10px;
}
form input{
margin-top:10px;
width:110px;
height:18px;
background:#eee;
}
form input.butt{
width:60px;
height:28px;
font-weight:bold;
}
#show{
margin-top:100px;
}
#show table{
width:380px;
margin:0 auto;
}
#show table td{
text-align:center;
}
5、PHP处理页面代码如下:
<?php
date_default_timezone_set("Asia/Shanghai"); //设置时区:东八区
$c=$_POST["contern"]; //获取表单提交过来的contern的值
if(empty($c)){ //如果$c为空
echo "<script type='text/javascript'>alert('留言内容不能为空');history.back();</script>"; //弹窗
}else{
$u=$_POST["user"]; //获取表单提交过来的user的值
if(empty($u)){ //如果$u为空
echo "<script type='text/javascript'>alert('留言用户不能为空');history.back();</script>"; //弹窗
}else{
$t=date("Y-m-d,H:m:s"); //获取时间
$c=trim($c); //去掉两端的空格
$c=htmlspecialchars($c); //把html标签转换为实体
$c=addslashes($c); //转义
$cc=mysqli_connect("localhost","root",""); //连接MySQL数据库
$db=mysqli_select_db($cc,"test"); //选择test数据库
$sql="insert into liuyan (name,content,time) values ('$u','$c','$t')";
$r=mysqli_query($cc,$sql); //执行SQL语句
if($r){ //如果SQL语句执行成功
echo "<script type='text/javascript'>alert('留言成功!');location.href('test27.php');</script>"; //弹窗
}else{
echo "<script type='text/javascript'>alert('留言失败');history.back();</script>"; //弹窗
}
mysqli_close($cc); //关闭数据库的连接
}
}
?>
6、PHP处理的过程如图27-2,27-3:

