所以我的谷歌饼图有这个代码(不包括饼图代码,但它工作正常并显示数据)
<?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],";
}
?>
我把回声放在不同的行中,但是如果它们在一行或两行中真的没关系,重要的是让它最终工作:) 而不是$ cat_id我想放置由此代码计算的SUM($ cat_amount):
$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'];
}
我尝试将while循环放入while循环中,在while循环中使用foreach循环,将$ cat_amount放入$ cat_id(仅显示一个SUM),依此类推。没有任何效果。我没有尝试过for循环,但我认为结果是相同的+我不确定如何定义循环需要运行的时间,因为可能有很多类型&#39; Expense&#39;类别及时添加。
非常感谢任何帮助。谢谢你,祝你有个美好的一天。
答案 0 :(得分:0)
也许我错过了什么,但看起来你可以在一个查询中加入这两个表
这将在一个查询/循环中获得所需的结果......
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],";
}
?>