douzi2749 2017-02-16 18:13
浏览 62
已采纳

将来自两个不同循环的数据放入谷歌饼图中

So I have this code for my Google pie chart (pie chart code not included, but it works fine and displays data)

<?php 
    $query = "SELECT * FROM category WHERE type = 'Expense' ";
    $select_category_list = mysqli_query($connection, $query);
    while($row = mysqli_fetch_assoc($select_category_list)) {
    $cat_id = $row['id'];
    $cat_title = $row['title']; 
   echo "['$cat_title'" . ",";
   echo "$cat_id],";
}
?>

I put the echo in different lines, but it really does not matter to if they are in one line or in two lines, what matters is to get it finally working :) Instead of $cat_id I want to put the SUM ($cat_amount) calculated by this code:

$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee
WHERE type = 'Expense' group by category_id ";
    $expense_query = mysqli_query($connection, $query);
    while ($row = mysqli_fetch_assoc($expense_query)) {
         $cat_amount = $row['TotalAmount'];
    }

I have tried putting while loop in a while loop, foreach loop in a while loop, putting $cat_amount instead of $cat_id (that only displays one SUM) and so on. Nothing worked. I have not tried the for loop, but I assume the result would be the same + I am not sure how would I define the times that the loop needs to run, since there could be many type 'Expense' categories added in time.

Any help would be very much appreciated. Thank you and have a lovely day.

  • 写回答

1条回答 默认 最新

  • douyou9923 2017-02-16 18:39
    关注

    maybe i'm missing something, but looks like you could join the two tables in one query

    this would get the desired result in one query / loop...

    sql:

    SELECT a.title as Title, SUM(b.amount) AS TotalAmount FROM category a, spendee b WHERE b.category_id = a.id and b.type = 'Expense' group by a.title

    php:

    <?php
      $query = "SELECT a.title as Title, SUM(b.amount) AS TotalAmount FROM category a, spendee b WHERE b.category_id = a.id and b.type = 'Expense' group by a.title";
      $select_category_list = mysqli_query($connection, $query);
      while ($row = mysqli_fetch_assoc($select_category_list)) {
        $cat_title = $row['Title'];
        $cat_amount = $row['TotalAmount'];
        echo "['$cat_title'" . ",";
        echo "$cat_amount],";
      }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?