实现商品评价和评价列表需要以下步骤:
1. 创建商品评价表和评价列表表,可以使用以下SQL语句:
“`
CREATE TABLE `product_reviews` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`rating` int(11) NOT NULL,
`comment` text NOT NULL,
`created_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `review_lists` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_id` int(11) NOT NULL,
`rating` int(11) NOT NULL,
`total_reviews` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
“`
2. 在商品详情页面添加评价表单,用户可以在此处填写评价信息并提交。可以使用以下代码:
“`
<form method="post" action="submit_review.php">
<input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
<label for="rating">评分:</label>
<select name="rating" id="rating">
<option value="1">1星</option>
<option value="2">2星</option>
<option value="3">3星</option>
<option value="4">4星</option>
<option value="5">5星</option>
</select>
<br>
<label for="comment">评价:</label>
<textarea name="comment" id="comment"></textarea>
<br>
<input type="submit" value="提交评价">
</form>
“`
3. 在submit_review.php文件中处理表单提交,将评价信息插入到商品评价表中,并更新评价列表表中的数据。可以使用以下代码:
“`
<?php
// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");
// 获取表单数据
$product_id = $_POST[‘product_id’];
$user_id = 1; // 假设当前用户ID为1
$rating = $_POST[‘rating’];
$comment = $_POST[‘comment’];
$created_at = date(‘Y-m-d H:i:s’);
// 插入评价数据
$sql = "INSERT INTO product_reviews (product_id, user_id, rating, comment, created_at) VALUES (‘$product_id’, ‘$user_id’, ‘$rating’, ‘$comment’, ‘$created_at’)";
mysqli_query($conn, $sql);
// 更新评价列表数据
$sql = "SELECT COUNT(*) AS total_reviews, AVG(rating) AS avg_rating FROM product_reviews WHERE product_id = ‘$product_id’";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$total_reviews = $row[‘total_reviews’];
$avg_rating = $row[‘avg_rating’];
$sql = "UPDATE review_lists SET rating = ‘$avg_rating’, total_reviews = ‘$total_reviews’ WHERE product_id = ‘$product_id’";
mysqli_query($conn, $sql);
// 关闭数据库连接
mysqli_close($conn);
// 跳转回商品详情页面
header("Location: product.php?id=$product_id");
?>
“`
4. 在商品列表页面显示评价信息,可以使用以下代码:
“`
<?php
// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");
// 查询评价列表数据
$sql = "SELECT * FROM review_lists";
$result = mysqli_query($conn, $sql);
// 显示评价列表
while ($row = mysqli_fetch_assoc($result)) {
$product_id = $row[‘product_id’];
$rating = $row[‘rating’];
$total_reviews = $row[‘total_reviews’];
echo "<p>商品ID:$product_id,评分:$rating,评价数量:$total_reviews</p>";
}
// 关闭数据库连接
mysqli_close($conn);
?>
“`
以上代码仅供参考,具体实现需要根据实际情况进行调整。