php评论功能怎么实现
数据库设计
创建评论表存储评论数据,表结构可包含以下字段:
id:自增主键content:评论内容(TEXT类型)user_id:用户ID(关联用户表)article_id:文章ID(关联文章表)created_at:评论时间(TIMESTAMP)
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
);
表单提交处理
创建评论提交表单:
<form action="submit_comment.php" method="post">
<textarea name="content" required></textarea>
<input type="hidden" name="article_id" value="<?= $article_id ?>">
<button type="submit">提交评论</button>
</form>
表单处理脚本(submit_comment.php):
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$content = htmlspecialchars($_POST['content']);
$article_id = intval($_POST['article_id']);
$user_id = $_SESSION['user_id']; // 假设用户已登录
// 数据库插入
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->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
$article_id = intval($_GET['id']);
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $pdo->prepare("SELECT c.*, u.username FROM comments c JOIN users u ON c.user_id = u.id WHERE article_id = ? ORDER BY created_at DESC");
$stmt->execute([$article_id]);
$comments = $stmt->fetchAll();
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<strong>' . htmlspecialchars($comment['username']) . '</strong>';
echo '<p>' . htmlspecialchars($comment['content']) . '</p>';
echo '<small>' . $comment['created_at'] . '</small>';
echo '</div>';
}
?>
安全增强
防止XSS攻击:
对所有用户输入使用htmlspecialchars()函数处理
防止SQL注入: 使用PDO预处理语句
限制评论频率:
// 检查最后评论时间
$stmt = $pdo->prepare("SELECT created_at FROM comments WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
$stmt->execute([$_SESSION['user_id']]);
$last_comment = $stmt->fetch();
if ($last_comment && (time() - strtotime($last_comment['created_at'])) < 60) {
die('评论过于频繁,请稍后再试');
}
分页功能
实现评论分页:
$per_page = 10;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $per_page;
$stmt = $pdo->prepare("SELECT SQL_CALC_FOUND_ROWS c.*, u.username FROM comments c JOIN users u ON c.user_id = u.id WHERE article_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $article_id, PDO::PARAM_INT);
$stmt->bindValue(2, $per_page, PDO::PARAM_INT);
$stmt->bindValue(3, $offset, PDO::PARAM_INT);
$stmt->execute();
$total = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();
$total_pages = ceil($total / $per_page);






