php mysql留言板实现
数据库设计
创建MySQL数据库表存储留言信息,表结构可包含字段:id(主键)、username(留言者姓名)、content(留言内容)、created_at(留言时间)。
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
数据库连接配置
创建config.php文件存放数据库连接信息,使用PDO扩展连接MySQL。
<?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("Database connection failed: " . $e->getMessage());
}
?>
提交留言功能
创建submit.php处理表单提交,过滤用户输入防止SQL注入。

<?php
require 'config.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 'config.php';
$stmt = $pdo->query("SELECT * FROM messages ORDER BY created_at DESC");
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<body>
<?php foreach ($messages as $message): ?>
<div class="message">
<strong><?= $message['username'] ?></strong>
<p><?= $message['content'] ?></p>
<small><?= $message['created_at'] ?></small>
</div>
<?php endforeach; ?>
</body>
</html>
前端表单设计
在页面中添加HTML表单供用户提交留言。

<form action="submit.php" method="post">
<input type="text" name="username" placeholder="Your name" required>
<textarea name="content" placeholder="Your message" required></textarea>
<button type="submit">Submit</button>
</form>
安全增强措施
添加CSRF防护和输入验证。
// 在config.php中添加
session_start();
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
// 在表单中添加
<input type="hidden" name="token" value="<?= $_SESSION['token'] ?>">
// 在submit.php中验证
if (!hash_equals($_SESSION['token'], $_POST['token'])) {
die("Invalid CSRF token");
}
分页功能实现
对留言列表添加分页支持。
$perPage = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$total = $pdo->query("SELECT COUNT(*) FROM messages")->fetchColumn();
$totalPages = ceil($total / $perPage);
$stmt = $pdo->prepare("SELECT * FROM messages ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $perPage, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();
样式优化
添加CSS美化留言板界面。
.message {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 10px;
border-radius: 5px;
}
form {
margin-bottom: 20px;
}






