PHP留言板
create table msg ( id int primary key auto_increment, name char(20), email char(30), content varchar(100) ) charset utf8;
1.php接收到的POST数据想办法写到mysql中; mysqli_connect — 打开一个到 MySQL 服务器的连接 mysqli_query — 发送一条 MySQL 查询
写入数据库 1.首先连接数据库
$conn = mysqli_connect('localhost','root','','test');//4个参数,服务器地址/用户名/密码/数据库名
2.告诉服务器我的客户端编码是多少[指的是当前使用的客户端编码]
mysqli_query($conn , 'set names utf8' );
3.将POST内容写入数据库,先将sql语句打印出来看看是否有错
$conn = mysqli_connect('localhost','root','','test'); mysql_query($conn,'set names utf8'); $sql = "insert into msg (name,email,content) values ('$_POST[name]' ,'$_POST[email]','$_POST[content]')"; //echo $sql; $res = mysqil_query($conn,$sql); if(!$res) { echo mysqli_error($link); } else { echo '留言发布成功'; }
4.如果我想读取数据库中的留言 不想重复写连mysql,选库,设置字符集 可以将其单独放在一个php文件中; conn.php的内容
$conn = mysqli_connect('localhost','root','','test');
mysql_query($conn,'set names utf8');
在php页面包含进来因为是必须要连接上 才能继续执行下面的代码,所以我们用require
require('./conn.php');
读取留言
mysqli_fetch _assoc — 从结果集中取得一行作为关联数组
require('./conn.php'); $sql = 'select * from msg'; $res = mysqli_query($conn,$sql); $data = array(); while($row = mysqli_fetch_assoc($res)) { $data[] = $row; } //print_r($data); include('./msglist.html');
模版中循环显示出留言内容:
<?php foreach($data as $d) {?> <tr> <td><?php echo $d['id'];?></td> <td><?php echo $d['name'];?></td> <td><span class="badge"><?php echo $d['email'];?></span></td> <td><?php echo $d['content'];?></td> <td><a href="msgdel.php?id=<?php echo $d['id'];?>">删除</a></td> <td><a href="msgedit.php?id=<?php echo $d['id'];?>">编辑</a></td> </tr> <?php }?>
留言删除 根据留言的主键id删除留言
require('./conn.php'); $id = $_GET['id']; $sql = "delete from msg where id=$id"; $res = mysqli_query($conn,$sql); if(!$res) { echo '留言删除失败'; } else { //echo '留言删除成功'; header('Location: msglist.php'); }
留言编辑
根据留言的主键id 编辑留言
注意:
模版应该同 发布留言的模版一致
不过: 该模版应该展现出原留言的内容
所以
1. 如果post 为空,即是点过来准备编辑留言 通过主键id 查询出该留言,以默认值的形式展现出来
2. 留言修改后,update 执行修改留言
require('./conn.php'); $id = $_GET['id']; if(empty($_POST)) { $sql = "select * from msg where id=$id"; $res = mysqli_query($conn,$sql); if(!$res) { echo mysqli_error($link); exit(); } $msg = mysqli_fetch_assoc($res); //print_r($msg); include('./msgedit.html'); } else { $sql = "update msg set name='$_POST[name]',email='$_POST[email]',content='$_POST[content]' where id=$id"; $res = mysqli_query($conn,$sql); if(!$res) { echo mysqli_error($link); } else { echo '留言修改成功'; } }
生而为人,与众不同