php商品评论怎么实现
实现商品评论功能的方法
数据库设计
创建评论表存储评论数据,表结构可包含以下字段:
comment_id:评论ID(主键)product_id:关联的商品IDuser_id:评论用户IDcontent:评论内容rating:评分(1-5星)created_at:评论时间
SQL创建表示例:
CREATE TABLE `product_comments` (
`comment_id` INT AUTO_INCREMENT PRIMARY KEY,
`product_id` INT NOT NULL,
`user_id` INT NOT NULL,
`content` TEXT NOT NULL,
`rating` TINYINT(1) DEFAULT 5,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`product_id`) REFERENCES `products`(`product_id`),
FOREIGN KEY (`user_id`) REFERENCES `users`(`user_id`)
);
前端表单设计
创建评论提交表单:

<form action="submit_comment.php" method="post">
<input type="hidden" name="product_id" value="<?= $product_id ?>">
<div class="rating">
<input type="radio" id="star5" name="rating" value="5"><label for="star5"></label>
<input type="radio" id="star4" name="rating" value="4"><label for="star4"></label>
<input type="radio" id="star3" name="rating" value="3"><label for="star3"></label>
<input type="radio" id="star2" name="rating" value="2"><label for="star2"></label>
<input type="radio" id="star1" name="rating" value="1"><label for="star1"></label>
</div>
<textarea name="content" required placeholder="请输入评论内容"></textarea>
<button type="submit">提交评论</button>
</form>
后端处理逻辑
创建submit_comment.php处理评论提交:
<?php
session_start();
require 'db_connection.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$product_id = filter_input(INPUT_POST, 'product_id', FILTER_VALIDATE_INT);
$user_id = $_SESSION['user_id'];
$content = htmlspecialchars(trim($_POST['content']));
$rating = filter_input(INPUT_POST, 'rating', FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 5]]);
if ($product_id && $user_id && $content && $rating) {
$stmt = $pdo->prepare("INSERT INTO product_comments
(product_id, user_id, content, rating) VALUES (?, ?, ?, ?)");
$stmt->execute([$product_id, $user_id, $content, $rating]);
header("Location: product.php?id=$product_id");
exit;
}
}
?>
评论展示功能
在商品页面显示评论列表:

<?php
$product_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($product_id) {
$stmt = $pdo->prepare("SELECT c.*, u.username
FROM product_comments c
JOIN users u ON c.user_id = u.user_id
WHERE c.product_id = ?
ORDER BY c.created_at DESC");
$stmt->execute([$product_id]);
$comments = $stmt->fetchAll();
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<h4>' . htmlspecialchars($comment['username']) . '</h4>';
echo '<div class="rating">' . str_repeat('★', $comment['rating']) . '</div>';
echo '<p>' . nl2br(htmlspecialchars($comment['content'])) . '</p>';
echo '<small>' . $comment['created_at'] . '</small>';
echo '</div>';
}
}
?>
安全与验证
实现必要的安全措施:
- 验证用户登录状态
- 防止XSS攻击(使用htmlspecialchars)
- 防止CSRF攻击(添加token验证)
- 限制评论频率(防止刷评)
- 敏感词过滤机制
高级功能扩展
可考虑添加以下高级功能:
- 评论回复功能
- 评论点赞系统
- 图片上传支持
- 管理员审核机制
- 评论分页加载
- 商品评分统计展示
注意事项
- 确保数据库连接使用PDO或MySQLi预处理语句防止SQL注入
- 对用户输入进行严格过滤和验证
- 考虑添加评论字数限制
- 实现友好的错误提示机制
- 对敏感操作进行日志记录






