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 ?

1

1 Answer 1

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.

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

1 Comment

Thank you very much

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.