php mysql留言板实现
实现PHP MySQL留言板的基本步骤
数据库设计与创建
创建一个名为message_board的数据库,包含messages表,字段可包括:
idINT(11) 自增主键usernameVARCHAR(50) 留言者名称contentTEXT 留言内容created_atTIMESTAMP 留言时间
SQL创建语句示例:
CREATE TABLE messages (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
数据库连接配置
创建config.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("数据库连接失败: " . $e->getMessage());
}
?>
留言提交处理
创建submit.php处理表单提交:
<?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>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="submit.php" method="post">
<input type="text" name="username" placeholder="您的姓名" required>
<textarea name="content" placeholder="留言内容" required></textarea>
<button type="submit">提交</button>
</form>
<div class="messages">
<?php foreach ($messages as $message): ?>
<div class="message">
<h3><?= $message['username'] ?></h3>
<p><?= $message['content'] ?></p>
<small><?= $message['created_at'] ?></small>
</div>
<?php endforeach; ?>
</div>
</body>
</html>
安全增强措施
输入验证与过滤
对所有用户输入使用htmlspecialchars()函数处理,防止XSS攻击:
$username = htmlspecialchars(trim($_POST['username']));
$content = htmlspecialchars(trim($_POST['content']));
防止SQL注入 使用PDO预处理语句处理所有数据库查询,避免直接拼接SQL语句:
$stmt = $pdo->prepare("INSERT INTO messages (username, content) VALUES (:username, :content)");
$stmt->execute([
':username' => $username,
':content' => $content
]);
功能扩展建议
分页显示 实现留言分页功能,修改查询语句:
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 5;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare("SELECT * FROM messages ORDER BY created_at DESC LIMIT :offset, :perPage");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute();
用户认证 添加简单的用户注册/登录系统:
// 用户表结构
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);
样式优化 添加CSS样式文件改善界面显示效果:
.messages {
margin-top: 20px;
}
.message {
border: 1px solid #ddd;
padding: 10px;
margin-bottom: 10px;
}






