计算mysql中的所有原始值

Idi*_*wIt 0 php mysql mysqli

我所做的就是将用户评级和评论保存到表格中,然后从数据库中调用它.现在我要做的是添加所有评级(例如:5 + 4 + 3 = 12),然后将它们除以评级计数(12/3 = 4)并获得平均评级或总评分.

我可以显示评论,但如何添加评级列中的所有值并获得平均值.

if (mysqli_num_rows($mesult) > 0) {
  $count = mysqli_num_rows($mesult);
  echo '<p class="">'.$count.' Reviews</p>';
  while($row = mysqli_fetch_assoc($mesult)) {
    $name =$row["name"];
    $text =$row["text"];
    $heading =$row["heading"];
    $rating =$row["rating"];
    echo '<div class="review"  itemscope itemtype="http://schema.org/Review">  <meta itemprop="itemReviewed" content ="'.$title.'"/> <p class="heading"><strong>'.$heading.'</strong></p><div class="ratings" itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating"> <meta itemprop="worstRating" content = "1"/><span itemprop="ratingValue">'.$rating.'</span>/<span itemprop="bestRating">5</span></div><p class="reviewtext" itemprop="description">'.$text.'</p><div class="reviewby"  itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">'.$name.'</span></div></div>';
}
Run Code Online (Sandbox Code Playgroud)

我也在询问的是

$loutput ="SELECT * FROM rating
WHERE product=$ID";
$mesult = mysqli_query($conns,$loutput);
Run Code Online (Sandbox Code Playgroud)

Emi*_*els 5

您还可以使用MySQL的AVG()来计算平均评分:

SELECT AVG(rating) AS avgRating FROM myTable;
Run Code Online (Sandbox Code Playgroud)

这是将结果舍入为X小数的方法:

 SELECT ROUND(AVG(rating), X) AS avgRating FROM myTable;
Run Code Online (Sandbox Code Playgroud)