简体   繁体   English

php sum列在多个表中,并作为一个总数返回

[英]php sum column in multiple tables and return as one total

I have a php code below that sum up the column going through multiple tables and return 3 separate total amounts after the query is done since I have 3 tables. 我下面有一个php代码,总结了经过多个表的列,由于我有3个表,查询完成后返回了3个单独的总数。 If I want to sum up those 3 total amounts into one, in what ways do I need to change the code to accomplish that? 如果我想将这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'];
}

Try something like this: 尝试这样的事情:

$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;

Just create a variable outside of the loop's scoop and add up to it. 只需在循环的范围之外创建一个变量并将其累加即可。

Try something like this. 尝试这样的事情。 Create a variable outside the loop, then increment it per loop. 在循环外创建一个变量,然后在每个循环中增加它。

$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;

Not sure if this works, but you get the idea. 不知道这是否行得通,但您知道了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM