php实现评论回复功能
数据库设计
创建两个表:comments 用于存储评论,replies 用于存储回复。comments 表结构:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
content TEXT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
replies 表结构:
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) ON DELETE CASCADE
);
添加评论功能
通过表单提交评论内容,插入到 comments 表中:
// 处理评论提交
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]);
}
显示评论列表
查询并显示所有评论:
$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 "<a href='#' onclick='showReplyForm(" . $comment['id'] . ")'>回复</a>";
// 显示回复表单(初始隐藏)
echo "<div id='reply-form-" . $comment['id'] . "' style='display:none;'>";
echo "<form method='POST' action='add_reply.php'>";
echo "<input type='hidden' name='comment_id' value='" . $comment['id'] . "'>";
echo "<textarea name='reply_content'></textarea>";
echo "<button type='submit'>提交回复</button>";
echo "</form>";
echo "</div>";
// 显示该评论的回复
$replies = $pdo->prepare("SELECT * FROM replies WHERE comment_id = ? ORDER BY created_at ASC");
$replies->execute([$comment['id']]);
foreach ($replies->fetchAll() as $reply) {
echo "<div class='reply'>";
echo "<p>" . htmlspecialchars($reply['content']) . "</p>";
echo "</div>";
}
echo "</div>";
}
添加回复功能
创建 add_reply.php 处理回复提交:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_content'])) {
$content = htmlspecialchars($_POST['reply_content']);
$comment_id = $_POST['comment_id'];
$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: comments.php"); // 返回评论页
exit();
}
前端交互
使用 JavaScript 切换回复表单的显示/隐藏:
function showReplyForm(commentId) {
var form = document.getElementById('reply-form-' + commentId);
form.style.display = form.style.display === 'none' ? 'block' : 'none';
}
样式优化
添加基础 CSS 样式区分评论和回复:
.comment {
border: 1px solid #ddd;
padding: 10px;
margin-bottom: 10px;
}
.reply {
margin-left: 30px;
border-left: 3px solid #eee;
padding-left: 10px;
margin-top: 5px;
}






