php +mysql 留言板


建表:
create table msg ( id int primary key auto_increment, name char(20), email char(30), content varchar(100) ) charset utf8;

$conn = mysql_connect('localhost','root','');//3个参数,服务器地址/用户名/密码

//告诉服务器我的客户端编码是多少[指的是当前使用的客户端编码]
mysql_query('use php0903' , $conn);

设置字符集
mysql_query('set names utf8' , $conn)


.将POST内容写入数据库,先将sql语句打印出来看看是否有错
$conn = mysql_connect('localhost','root',''); mysql_query('use blog' , $conn); mysql_query('set names utf8' , $conn);
$sql = "insert into msg (name,email,content) values ('$_POST[name]' ,'$_POST[email]','$_POST[content]')"; //echo $sql;
$rs = mysql_query($sql); if(!$rs) {    echo mysql_error(); } else {    echo '留言发布成功';


读取数据库中的留言
require('./conn.php'); $sql = 'select * from msg'; $rs = mysql_query($sql);
$data = array(); while($row = mysql_fetch_assoc($rs)) {    $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";
if(!mysql_query($sql)) {    echo '留言删除失败';
} else {
    //echo '留言删除成功';    header('Location: msglist.php');
}


留言编辑
require('./conn.php');
$id = $_GET['id'];
if(empty($_POST)) {   
$sql = "select * from msg where id=$id";    $rs = mysql_query($sql);    if(!$rs) {        echo mysql_error();        exit();    }    $msg = mysql_fetch_assoc($rs);    //print_r($msg);    include('./msgedit.html'); } else {    $sql = "update msg set name='$_POST[name]',email='$_POST[email]',content='$_POST[content]' where id=$id";       if(!mysql_query($sql)) {        echo mysql_error();    } else {        echo '留言修改成功';    } }










你可能感兴趣的:(php +mysql 留言板)