php实现帖子回复
PHP实现帖子回复功能
数据库设计
创建帖子表和回复表,帖子表存储主贴信息,回复表存储回复内容及关联的帖子ID。
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE replies (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts(id)
);
表单提交处理
创建回复表单,提交到处理脚本。表单需包含回复内容和关联的帖子ID。

<form action="submit_reply.php" method="post">
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
<textarea name="content" required></textarea>
<button type="submit">提交回复</button>
</form>
回复处理脚本
接收表单数据并插入数据库。需进行数据验证和防SQL注入处理。
// submit_reply.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post_id = filter_input(INPUT_POST, 'post_id', FILTER_VALIDATE_INT);
$content = trim($_POST['content']);
if ($post_id && !empty($content)) {
$db = new PDO('mysql:host=localhost;dbname=forum', 'username', 'password');
$stmt = $db->prepare("INSERT INTO replies (post_id, content) VALUES (?, ?)");
$stmt->execute([$post_id, $content]);
header("Location: view_post.php?id=" . $post_id);
exit;
}
}
显示回复内容
在帖子详情页查询并显示所有回复。

// view_post.php
$post_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($post_id) {
$db = new PDO('mysql:host=localhost;dbname=forum', 'username', 'password');
// 获取主贴
$post = $db->query("SELECT * FROM posts WHERE id = $post_id")->fetch();
// 获取回复
$replies = $db->query("SELECT * FROM replies WHERE post_id = $post_id ORDER BY created_at DESC")->fetchAll();
// 显示帖子及回复
echo "<h1>{$post['title']}</h1>";
echo "<p>{$post['content']}</p>";
foreach ($replies as $reply) {
echo "<div class='reply'>";
echo "<p>{$reply['content']}</p>";
echo "<small>{$reply['created_at']}</small>";
echo "</div>";
}
}
安全增强
使用预处理语句防止SQL注入,对输出内容进行转义防止XSS攻击。
// 输出转义
function escape($data) {
return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}
// 在显示内容时使用
echo escape($post['content']);
分页功能
当回复数量较多时,添加分页支持。
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;
$stmt = $db->prepare("SELECT * FROM replies WHERE post_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $post_id, PDO::PARAM_INT);
$stmt->bindValue(2, $per_page, PDO::PARAM_INT);
$stmt->bindValue(3, $offset, PDO::PARAM_INT);
$stmt->execute();
$replies = $stmt->fetchAll();






