php实现简单留言板
数据库设计
创建一个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
);
前端表单
构建HTML表单用于提交留言:

<form method="post" action="submit.php">
<input type="text" name="username" placeholder="您的姓名" required>
<textarea name="content" placeholder="留言内容" required></textarea>
<button type="submit">提交留言</button>
</form>
处理提交数据
创建submit.php处理表单提交:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username']);
$content = htmlspecialchars($_POST['content']);
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO messages (username, content) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $content);
$stmt->execute();
$stmt->close();
$conn->close();
header("Location: index.php");
}
?>
显示留言列表
创建index.php显示所有留言:

<?php
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM messages ORDER BY created_at DESC");
while ($row = $result->fetch_assoc()) {
echo '<div class="message">';
echo '<h3>' . htmlspecialchars($row['username']) . '</h3>';
echo '<p>' . htmlspecialchars($row['content']) . '</p>';
echo '<small>' . $row['created_at'] . '</small>';
echo '</div>';
}
$conn->close();
?>
安全增强
添加CSRF防护和输入验证:
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("CSRF验证失败");
}
// 其他验证逻辑...
}
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
样式优化
添加基础CSS美化留言板:
.message {
border: 1px solid #ddd;
padding: 15px;
margin-bottom: 10px;
border-radius: 5px;
}
form {
margin-bottom: 20px;
}
textarea {
width: 100%;
min-height: 100px;
}






