php实现评论功能
数据库设计
创建评论表(示例结构):
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`content` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`parent_id` int(11) DEFAULT NULL COMMENT '回复的评论ID',
`post_id` int(11) NOT NULL COMMENT '关联的文章或内容ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
表单提交处理
创建评论提交表单(HTML部分):
<form action="submit_comment.php" method="POST">
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
<textarea name="content" required></textarea>
<button type="submit">提交评论</button>
</form>
PHP处理逻辑(submit_comment.php):
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$content = htmlspecialchars($_POST['content']);
$post_id = intval($_POST['post_id']);
$user_id = $_SESSION['user_id'] ?? 0; // 假设用户已登录
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $pdo->prepare("INSERT INTO comments (user_id, content, post_id) VALUES (?, ?, ?)");
$stmt->execute([$user_id, $content, $post_id]);
header("Location: post.php?id=".$post_id); // 返回原页面
}
?>
评论列表展示
从数据库查询并显示评论:
<?php
$post_id = intval($_GET['id']);
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $pdo->prepare("SELECT * FROM comments WHERE post_id = ? ORDER BY created_at DESC");
$stmt->execute([$post_id]);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<p>'.htmlspecialchars($comment['content']).'</p>';
echo '<small>用户ID: '.$comment['user_id'].' | 时间: '.$comment['created_at'].'</small>';
echo '</div>';
}
?>
回复功能实现
扩展表单支持回复:
<form action="submit_comment.php" method="POST">
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
<input type="hidden" name="parent_id" value="<?php echo $_GET['reply_to'] ?? 0; ?>">
<textarea name="content" required></textarea>
<button type="submit">提交</button>
</form>
更新数据库插入逻辑:
$parent_id = isset($_POST['parent_id']) ? intval($_POST['parent_id']) : null;
$stmt = $pdo->prepare("INSERT INTO comments (user_id, content, post_id, parent_id) VALUES (?, ?, ?, ?)");
$stmt->execute([$user_id, $content, $post_id, $parent_id]);
嵌套评论展示
递归显示评论及回复:
function displayComments($comments, $parent_id = null) {
foreach ($comments as $comment) {
if ($comment['parent_id'] == $parent_id) {
echo '<div class="comment" style="margin-left: '.($parent_id ? '20px' : '0').'">';
echo '<p>'.htmlspecialchars($comment['content']).'</p>';
echo '<a href="?id='.$comment['post_id'].'&reply_to='.$comment['id'].'">回复</a>';
displayComments($comments, $comment['id']); // 递归调用
echo '</div>';
}
}
}
displayComments($comments);
安全注意事项
- 始终使用预处理语句防止SQL注入
- 输出内容时使用
htmlspecialchars()过滤XSS攻击 - 验证用户权限,确保登录后才能评论
- 对高频提交实施限流措施
性能优化建议
- 为
post_id和parent_id字段添加索引 - 实现分页查询避免一次性加载大量评论
- 考虑使用缓存机制存储热门帖子的评论
完整实现需根据实际项目需求调整数据库结构和业务逻辑。







