douyi1855 2016-09-14 22:07
浏览 27
已采纳

pdo php addison与来自同一领域的存储变量[关闭]

Adding togeather all ratings from my results.

Ok I have a table called ratings and in the table it is layed out like this.

     ID | UserID | Rating | TMDB |  TYPE
     -----------------------------------
     1      34        6     432      3
     -----------------------------------
     2      34        9     432      3

My sql is

$sql = "SELECT * FROM `tbl_rating` WHERE `tmdb`='" . $tmdb . "' AND `type`='" . $type . "' ";

ok this pulls up the information I want. I can now use a while or foreach command to call $row['rating']. However I dont know how I can add the results togeather or do any basic math. This is a movie rating database and I am trying to get my script to add togeather all the "ratings" in the results column and then work out the average vote.

I hope this make scence. Any help would be great thank you all!

this script has star rating for Gore, Scare, Acting, Story (this is the where I use the type field).

  • 写回答

1条回答 默认 最新

  • dongtou2097 2016-09-14 22:23
    关注

    Add to a variable containing the total.

    $total_rating = 0;
    $rating_count = 0;
    while ($row = $stmt->fetch()) {
        $total_rating += $row['rating'];
        $rating_count++;
    }
    if ($rating_count > 0) {
        $avg_rating = $total_rating / $rating_count;
    } else {
        $avg_rating = 0;
    }
    

    You could also just do this in the query:

    $sql = "SELECT AVG(rating) AS avg_rating FROM `tbl_rating` WHERE `tmdb`= :tmdb AND `type`= :type ";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':tmdb', $tmdb);
    $stmt->bindParam(':type', $type);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $avg_rating = $row['avg_rating'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。