php+mysql 实现简单留言表的写入与删除

2021-09-07 Views php | mysql688字4 min read

新建一个message数据库,如图

留言板页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>留言板</title>
</head>
<body>
  <div class="content"> 
  <div><a href="./list.php">留言列表</a></div>
    <form method="POST" action="./send.php">
      <div>用户名:<input type="text"  name="user"></div>
      <div>标题:<input type="text" name="title"></div>
      <div>内容:<textarea name="content"></textarea></div>
      <input type="submit" name="submit" value="发布留言">
      </div> 
    </form>
 </body>
</html>


php连接数据库

conn.php

<?php

$conn =  mysqli_connect ("localhost", "server", "key", "username");

/* 检测数据库连接是否成功
if(!$conn){
    die(!'fail !').mysqli_error();
}else{
    echo 'connect !';
}
*/

mysqli_query($conn, "set names 'utf8");

?>`

写入数据

send.php

<?php

var_dump($_POST);
include('conn.php');
$id = $_POST['id'];
$user = $_POST['user'];
$title = $_POST['title'];
$content = $_POST['content'];

if($_POST){

	$sql = "insert into message(name,title,content,
	createtime)values('$user','$title','$content',now())";
	$res = mysqli_query($conn,$sql);
	//var_dump($res);die;
	if(!$res){
          echo "<script>
              alert('留言发布失败');location.href='./index.html';
		  </script>";
	}else{ 
		//echo "<script>alert('留言发布成功');location.href='./list.php';</script>";
		echo  "<script>location.href='./list.php';</script>";
	}
}
   
?>

删除数据

del.php

<?php
include("conn.php");

$id = $_GET['id'];

$sql = "delete from message where id=".$id;

mysqli_query($conn,$sql);

echo "<script>";
echo "location.href='list.php'";
echo "</script>";

?>

留言列表

list.php

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>留言列表</title>
     <?php include("./conn.php") ?>
</head>
<body>
     <div style="width:60%;margin: auto;">留言列表</div><hr>
     <table style="width: 50%;margin: auto;
     border: 1px solid #ccc;margin-top: 200px;">
     	   <tr border='1'>
     	   	  <td>ID</td>
     	   	  <td>留言标题</td>
               <td>用户名</td>
              <td>留言内容</td>
              <td>留言时间</td>
               <td>操作</td>
     	   </tr>
             <?php 
              $sql = "select * from message order by id desc";
              $res = mysqli_query($conn,$sql);
              //var_dump($res);

              while ($row = mysqli_fetch_array($res)) {
             ?>
     	   <tr border='1'>
              <td><?php echo $row['id'];?></td>
              <td><?php echo $row['title'];?></td>
              <td><?php echo $row['name'];?></td>
              <td><?php echo $row['content'];?></td>
              <td><?php echo $row['createtime'];?></td>
              <td><a href="del.php?id=<?php echo $row['id'];?>">删除</a></td>    
             </tr>
          <?php  } ?>
          
          <tr border='2'>
               <td><a href="./">返回留言</a></td>
          </tr>
        

     </table>
</body>
</html>
EOF