我试图为我的网站创建一个评论系统,我想从我最近的5条评论中得到一个平均数,第一部分工作正常,如果我删除了AVG我没有得到任何错误只是最后一个数字的值我进入了数据库。一旦我添加了AVG,它就会给我未定义的索引:评级第23行?
任何帮助都将非常感谢 继承人代码:
// collect 5 lastest reviews for viewing
$reviews = "";
$sqli = mysqli_query($conn, "SELECT review, reviewer_name, review_date FROM reviews WHERE review_id='$id' ORDER BY review_date DESC LIMIT 5");
$reviewCount = mysqli_num_rows($sqli); // count the output amount
if($reviewCount > 0) {
//get all the product details
while($row = mysqli_fetch_array($sqli)){
$review = $row["review"];
$reviewer_name = $row['reviewer_name'];
$review_date = $row['review_date'];
$reviews .= ''.$review.''.$reviewer_name.''.$review_date.'<br />';
}
}
$rating = "";
$test = mysqli_query($conn, "SELECT AVG(rating) FROM reviews WHERE review_id='$id' ORDER BY review_date DESC LIMIT 5");
$ratingCount = mysqli_num_rows($test); // count the output amount
if($ratingCount > 0) {
while($row = mysqli_fetch_array($test)){
$rating = $row["rating"];
}
}
答案 0 :(得分:1)
输出中没有名为rating
的列。使用列别名:
SELECT AVG(rating) as rating
FROM reviews
WHERE review_id = '$id';
请注意,order by
和limit
没用,因为没有group by
的聚合查询只返回一行。