我有一个PHP代码,它总结了通过多个表的列,并在查询完成后返回3个单独的总金额,因为我有3个表。如果我想将这3个总金额合并为一个,我需要以什么方式更改代码才能实现这一目标?
foreach($result as $row) {
$stmt1 = $DB_CON_C->prepare("SELECT SUM(total_fee) AS total_amount FROM `".$row['files']."`");
$stmt1->execute();
$sum1 = $stmt1->fetch(PDO::FETCH_ASSOC);
echo $sum1['total_amount'];
}
答案 0 :(得分:2)
尝试这样的事情:
$totalAmount = 0;
foreach($result as $row) {
$stmt1 = $DB_CON_C->prepare("SELECT SUM(total_fee) AS total_amount FROM `".$row['files']."`");
$stmt1->execute();
$sum1 = $stmt1->fetch(PDO::FETCH_ASSOC);
totalAmount += $sum1['total_amount'];
}
echo $totalAmount;
只需在循环搜索之外创建一个变量并加起来即可。
答案 1 :(得分:1)
尝试这样的事情。在循环外创建一个变量,然后按循环递增它。
$grandTotal = 0;
foreach($result as $row) {
$stmt1 = $DB_CON_C->prepare("SELECT SUM(total_fee) AS total_amount FROM `".$row['files']."`");
$stmt1->execute();
$sum1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$grandTotal = $grandTotal + $sum1['total_amount'];
}
echo $grandTotal;
不确定这是否有效,但你明白了。