1

I have this code and i would like to get total combination of all categories

my code so far

     for ($k = 0; $k < 4; $k++) {   

     $result= $DB->query("SELECT total FROM ".$DB->prefix("mystat")." WHERE year='$year' AND category='$categoryname[$k]'");
               $row = $DB->fetchArray($result);
           $total=$row['total'];   
echo $total++;
     }

let say i have this data

A - 1
B - 2
C - 3

my current output

123

my desired output

6

How do i correct this ?

gtroop
  • 295
  • 4
  • 13
  • 1
    https://stackoverflow.com/questions/1496682/how-to-sum-values-of-the-array-of-the-same-key please have a look at this . this may help you . – Pranav MS Jul 27 '17 at 04:37

1 Answers1

1

It is because you are doing echo in loop. And also you logic is wrong. change your code like:

$total = 0;
for ($k = 0; $k < 4; $k++) {
    $result= $DB->query("SELECT total FROM ".$DB->prefix("mystat")." WHERE year='$year' AND category='$categoryname[$k]'");
    $row = $DB->fetchArray($result);
    $total +=$row['total'];   
}
echo $total; // DO echo here

Also if you don't need categories and total separately and only need sum of all then its better to use SUM with group by category in sql.

B. Desai
  • 16,414
  • 5
  • 26
  • 47