php商品评论怎么实现
实现PHP商品评论功能
数据库设计 创建商品评论表,包含字段如评论ID、用户ID、商品ID、评论内容、评分、评论时间等。
CREATE TABLE `product_reviews` (
`review_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`content` text NOT NULL,
`rating` tinyint(1) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`review_id`),
KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
前端表单 创建评论提交表单,包含评分选择和评论内容输入框。
<form action="submit_review.php" method="post">
<input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
<div class="rating">
<input type="radio" id="star5" name="rating" value="5">
<label for="star5"></label>
<!-- 其他星级选项 -->
</div>
<textarea name="content" required></textarea>
<button type="submit">提交评论</button>
</form>
后端处理 创建submit_review.php处理表单提交,验证数据并存入数据库。
// 验证用户登录
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
// 获取并过滤输入
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$content = htmlspecialchars(trim($_POST['content']));
$rating = filter_input(INPUT_POST, 'rating', FILTER_VALIDATE_INT,
array('options' => array('min_range' => 1, 'max_range' => 5)));
// 数据验证
if (!$product_id || !$content || !$rating) {
die('无效的输入参数');
}
// 数据库插入
try {
$stmt = $pdo->prepare("INSERT INTO product_reviews
(user_id, product_id, content, rating)
VALUES (?, ?, ?, ?)");
$stmt->execute([$_SESSION['user_id'], $product_id, $content, $rating]);
header("Location: product.php?id=$product_id");
} catch (PDOException $e) {
die("数据库错误: " . $e->getMessage());
}
评论显示 在商品页面显示所有评论,按时间倒序排列。
// 获取商品评论
$stmt = $pdo->prepare("SELECT r.*, u.username
FROM product_reviews r
JOIN users u ON r.user_id = u.user_id
WHERE product_id = ?
ORDER BY created_at DESC");
$stmt->execute([$product_id]);
$reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 显示评论
foreach ($reviews as $review) {
echo '<div class="review">';
echo '<h4>' . htmlspecialchars($review['username']) . '</h4>';
echo '<div class="rating">' . str_repeat('★', $review['rating']) . '</div>';
echo '<p>' . nl2br(htmlspecialchars($review['content'])) . '</p>';
echo '<small>' . $review['created_at'] . '</small>';
echo '</div>';
}
安全性考虑
- 使用预处理语句防止SQL注入
- 对输出内容进行HTML转义
- 验证用户输入数据
- 实现CSRF保护
- 限制未登录用户提交评论
扩展功能建议

- 实现评论回复功能
- 添加评论审核机制
- 支持图片上传
- 实现评论点赞功能
- 添加评论分页显示






