0

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. 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?

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'];
}
3
  • Your code is vulnerable to attacks. The advantage of using prepare statement is so that you can bindParams Commented May 11, 2017 at 5:10
  • If not in SQL, you could just add up $sum1in PHP. Commented May 11, 2017 at 5:11
  • @FrenchMajesty - You can't bind column names (which the OP is inserting) using prepared statements. The column names should never be injected using user inputs, though. There are safer ways to do it, like having a "white list" of column names that are acceptable. Commented May 11, 2017 at 5:14

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This works perfectly when added the missing $ before totalAmount.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.