php 实现评论
PHP 实现评论功能
评论功能是网站常见的交互模块,可以通过PHP结合数据库实现。以下是一个基础的实现方案:
数据库设计
需要创建评论表存储数据,基本字段包括:
id:主键,自增content:评论内容user_id:用户IDarticle_id:关联文章IDcreated_at:创建时间
SQL创建语句示例:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
content TEXT NOT NULL,
user_id INT NOT NULL,
article_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
评论表单
前端HTML表单示例:
<form action="submit_comment.php" method="post">
<input type="hidden" name="article_id" value="<?php echo $article_id; ?>">
<textarea name="content" required></textarea>
<button type="submit">提交评论</button>
</form>
处理提交
创建submit_comment.php处理表单提交:
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
// 获取表单数据
$content = $_POST['content'];
$article_id = $_POST['article_id'];
$user_id = $_SESSION['user_id']; // 假设用户已登录
// 插入数据库
$stmt = $db->prepare("INSERT INTO comments (content, user_id, article_id) VALUES (?, ?, ?)");
$stmt->execute([$content, $user_id, $article_id]);
// 重定向回文章页
header("Location: article.php?id=$article_id");
?>
显示评论
在文章页显示评论:

<?php
// 获取文章ID
$article_id = $_GET['id'];
// 查询评论
$stmt = $db->prepare("SELECT * FROM comments WHERE article_id = ? ORDER BY created_at DESC");
$stmt->execute([$article_id]);
$comments = $stmt->fetchAll();
// 显示评论
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<p>' . htmlspecialchars($comment['content']) . '</p>';
echo '<small>发布于 ' . $comment['created_at'] . '</small>';
echo '</div>';
}
?>
安全注意事项
- 使用预处理语句防止SQL注入
- 输出内容时使用
htmlspecialchars()防止XSS攻击 - 对用户权限进行验证
- 实现CSRF防护
扩展功能
- 评论回复功能:添加
parent_id字段实现嵌套评论 - 评论审核:添加
status字段管理评论状态 - 富文本编辑:集成编辑器如TinyMCE
- 分页显示:实现评论分页加载
以上实现提供了基础评论功能的核心代码,可根据实际需求进行扩展和优化。






