1

I have a MySQL DB

I would like to get the sum or totals of values in my columns I need to echo it to be used in Google Graphs

This is my current code

 <?php 
        $query = "SELECT * from activation";

         $exec = mysqli_query($con,$query);
         while($row = mysqli_fetch_array($exec)){

         echo "['".$row['type']."',".$sum['type']."],"; 
         }
         ?> 

The row Type is the ones I want to get SUM on their values differ from HIJACKING ACCIDENT and so forth values are constant.

The $sum I know is wrong but this is where I need to echo the totals of row type

The following code worked

 <?php 
            $query = "SELECT type, count(type) from activation group by type";

             $exec = mysqli_query($con,$query);
             while($row = mysqli_fetch_array($exec)){

             echo "['".$row['type']."',".$row['count(type)']."],";
             }
             ?> 
7
  • 2
    why don't you SUM() in the query instead? Commented Dec 29, 2018 at 14:48
  • 1
    ^^ this or $sum += $row['type']; (initalize $sum=0 before the while) - then echo $sum Commented Dec 29, 2018 at 14:53
  • How about SELECT type, count(type) from activation group by type? Commented Dec 29, 2018 at 14:53
  • 1
    your echo line looks like you try to construct a json string. Don't do that. Build an array, then json_encode that. Commented Dec 29, 2018 at 14:54
  • @Curious_Mind Your string gives me the results I need when I place in HeidiSQL but how will I echo the values then to the graph as per the echo? Commented Dec 29, 2018 at 14:56

1 Answer 1

1

I guess this is the more precise code that you should use. I used alias of your count(type) as act_type. Hope this helps :)

<?php 
    $query = "SELECT type, count(type) as act_type from activation group by type";
    $exec = mysqli_query($con,$query);
    $expected = [];
    while($row = mysqli_fetch_array($exec)){
         $expected[$row['type']] = $row['act_type'];
         echo "['".$row['type']."',".$row['act_type']."],"; // you can use this line just for printing purpose
   }
   // use $expected array as you wish any where in your code, it contains your result as key=>value manner
?> 
Sign up to request clarification or add additional context in comments.

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.