gtroop
gtroop

Reputation: 293

Getting total from mysql query with array

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 ?

Upvotes: 1

Views: 25

Answers (1)

B. Desai
B. Desai

Reputation: 16436

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.

Upvotes: 1

Related Questions