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 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测