php mysql留言板实现
实现PHP MySQL留言板
数据库设计
创建MySQL数据库表存储留言信息,表结构如下:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
连接数据库
创建数据库连接文件db_connect.php:
<?php
$host = 'localhost';
$dbname = 'message_board';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
提交留言处理
创建submit.php处理表单提交:
<?php
require 'db_connect.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username']);
$content = htmlspecialchars($_POST['content']);
$stmt = $pdo->prepare("INSERT INTO messages (username, content) VALUES (?, ?)");
$stmt->execute([$username, $content]);
header('Location: index.php');
exit;
}
?>
显示留言列表
创建index.php显示所有留言:
<?php
require 'db_connect.php';
$stmt = $pdo->query("SELECT * FROM messages ORDER BY created_at DESC");
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="submit.php" method="post">
姓名: <input type="text" name="username" required><br>
内容: <textarea name="content" required></textarea><br>
<button type="submit">提交</button>
</form>
<hr>
<?php foreach ($messages as $message): ?>
<div>
<strong><?= $message['username'] ?></strong>
<small><?= $message['created_at'] ?></small>
<p><?= $message['content'] ?></p>
</div>
<?php endforeach; ?>
</body>
</html>
安全增强措施
添加CSRF防护和输入验证:
session_start();
// 生成CSRF令牌
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// 验证CSRF令牌
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die('CSRF token validation failed');
}
}
样式优化
添加基础CSS样式:
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
form {
margin-bottom: 20px;
}
textarea {
width: 100%;
height: 100px;
}
.message {
border-bottom: 1px solid #eee;
padding: 10px 0;
}
这个实现包含了留言板的基本功能:数据库连接、留言提交、留言显示以及基本的安全防护措施。可以根据需要进一步扩展功能,如用户注册登录、留言编辑删除、分页显示等。







