php实现评论回复功能
数据库设计
创建两个表:comments 存储评论,replies 存储回复。comments 表包含主键 id、content(评论内容)、user_id(用户ID)和 created_at(创建时间)。replies 表包含主键 id、comment_id(关联的评论ID)、content(回复内容)、user_id(用户ID)和 created_at(创建时间)。
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
content TEXT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE replies (
id INT AUTO_INCREMENT PRIMARY KEY,
comment_id INT NOT NULL,
content TEXT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (comment_id) REFERENCES comments(id)
);
提交评论
通过表单提交评论内容,后端使用 PHP 处理并存入数据库。确保对用户输入进行过滤,防止 SQL 注入。
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['comment'])) {
$content = htmlspecialchars($_POST['comment']);
$user_id = $_SESSION['user_id']; // 假设用户已登录
$stmt = $pdo->prepare("INSERT INTO comments (content, user_id) VALUES (?, ?)");
$stmt->execute([$content, $user_id]);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
显示评论及回复
查询评论列表,并为每条评论查询关联的回复。使用嵌套循环展示评论和回复。
<?php
$comments = $pdo->query("SELECT * FROM comments ORDER BY created_at DESC")->fetchAll();
foreach ($comments as $comment) {
echo "<div class='comment'>";
echo "<p>".htmlspecialchars($comment['content'])."</p>";
echo "<form method='POST' action='reply.php'>";
echo "<input type='hidden' name='comment_id' value='".$comment['id']."'>";
echo "<textarea name='reply_content' placeholder='回复内容'></textarea>";
echo "<button type='submit'>回复</button>";
echo "</form>";
$replies = $pdo->prepare("SELECT * FROM replies WHERE comment_id = ? ORDER BY created_at");
$replies->execute([$comment['id']]);
foreach ($replies->fetchAll() as $reply) {
echo "<div class='reply'>";
echo "<p>".htmlspecialchars($reply['content'])."</p>";
echo "</div>";
}
echo "</div>";
}
?>
处理回复
创建 reply.php 文件处理回复提交,将回复内容关联到对应评论。
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_content'])) {
$comment_id = (int)$_POST['comment_id'];
$content = htmlspecialchars($_POST['reply_content']);
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("INSERT INTO replies (comment_id, content, user_id) VALUES (?, ?, ?)");
$stmt->execute([$comment_id, $content, $user_id]);
header("Location: ".$_SERVER['HTTP_REFERER']);
exit;
}
?>
前端优化
使用 AJAX 实现无刷新提交和加载评论回复。通过 JavaScript 监听表单提交事件,异步发送请求并动态更新页面内容。
document.querySelectorAll('form').forEach(form => {
form.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
fetch(this.action, {
method: 'POST',
body: formData
}).then(response => {
location.reload();
});
});
});
安全性增强
对用户输入进行验证和过滤,使用预处理语句防止 SQL 注入。对输出内容使用 htmlspecialchars 防止 XSS 攻击。
$content = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
$user_id = filter_var($_SESSION['user_id'], FILTER_VALIDATE_INT);






