0

I have tried for several hours to get MySQL data in a Google charts but I can't wrap my head around how to make a working page from the examples I've come across on the internet.

To start fresh I took a example from Google charts and manually filled it with data. This gives me the graph I want to have. the Google charts graph is generated by a simple HTML PAGE (JUST THE VARIABLE PART:

....
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['date',          'Baxico'    ,   'Degriek'   ,    'Foldman'  ,   'Madmeijs'  ,   'Marcello'  ,   'Meijster'  ,   'Pokermom'],
          ['110415180035',  38,             1,              16,             10,             6,              4,              25        ],
          ['110415190222',  38,             16,             6,              4,              1,              25,             10        ],
          ['110415200747',   6,             38,             25,             10,             1,              16,             4         ],
          ['110415211933',  10,             38,             6,              25,             4,              16,             1         ],
          ['110415222033',  16,             1,              10,             6,              38,             25,             4         ],
          ['110415232833',  38,             4,              1,              25,             10,             6,              16        ]
        ]);

        

I made the same data output in MySQL:

select tournamentid
,(select points  from pokermax_scores as t2 where playerid = 'Baxico' and t1.tournamentid = t2.tournamentid) as Baxico
,(select points  from pokermax_scores as t2 where playerid = 'Degriek' and t1.tournamentid = t2.tournamentid) as Degriek
,(select points  from pokermax_scores as t2 where playerid = 'Foldman' and t1.tournamentid = t2.tournamentid) as Foldman
,(select points  from pokermax_scores as t2 where playerid = 'Madmeijs' and t1.tournamentid = t2.tournamentid) as Madmeijs
,(select points  from pokermax_scores as t2 where playerid = 'Marcello' and t1.tournamentid = t2.tournamentid) as Marcello
,(select points  from pokermax_scores as t2 where playerid = 'Meijster' and t1.tournamentid = t2.tournamentid) as Meijster
,(select points  from pokermax_scores as t2 where playerid = 'Pokermom' and t1.tournamentid = t2.tournamentid) as Pokermom
from pokermax_scores as t1
group by tournamentid

which results in same data: http://i60.tinypic.com/6nqp76.png

But I can't get the data loaded as shown in this example: http://datamakessense.com/google-charts-api-from-your-sql-database-to-a-live-chart-with-no-coding-skills/

I can make the database connection, and paste in the SQL, but I'm unclear how to set the script so it takes the data from the SQL.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Jorn
  • 13
  • 7
  • 1
    Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Apr 30 '15 at 13:29
  • Sidenote: You have a lot of curly quotes `‘’` `“ ”` `″` which is killing your code. Did you code this in some kind of Word Processor or just a bad paste? – Funk Forty Niner Apr 30 '15 at 13:31
  • please include only relevant code because your question is too long and its really hard to give answer with current form of your question **good read** http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ – NullPoiиteя Apr 30 '15 at 13:33
  • This one's gone stale, *so it seems Sam* - @JayBlanchard – Funk Forty Niner Apr 30 '15 at 14:43
  • *Righto Ralph.* I believe it went stale from the outset @Fred-ii- – Jay Blanchard Apr 30 '15 at 14:44
  • Those curlys are not helping them neither *Sam* - @JayBlanchard – Funk Forty Niner Apr 30 '15 at 14:45
  • *It's kinda' a mess Ralph.* The code could stand a bit of dusting @Fred-ii- – Jay Blanchard Apr 30 '15 at 14:46
  • Yeah, and then some *cough, cough* - Sorry, just coming out of a huge cloud here *Sam* - @JayBlanchard – Funk Forty Niner Apr 30 '15 at 14:47
  • curlies come from the sample code i copy pasted from the webpage. Basicly the first code block is the google code that i edited to show my graph with manual data. the second block is my SQL , you can see the result in the image pasted below that, and the last codeblock is just example I found off the internet (well looked at over 20 examples , but this one seemed close to my wish. If you need more information let me know. I will shorten my Question now. – Jorn Apr 30 '15 at 18:14

1 Answers1

1

Hey buddy i had the same problem, what you are trying to do is to take the tournamentid and draw for every data column a line, bar, column or whatever this problem called "pivot table" try to search over the internet, there is two different solutions for this :

  1. You can solve this in google charts api using javascript.
  2. You can solve this by nested loops(for loops) + using two selects.

Check the code below: using the second solution.

<?php
    /* Connect  to database */
    $mysqli = new mysqli("localhost","root","123","charts");
    if(mysqli_connect_errno()){
      trigger_error('Connection failed: '.$mysqli->error);
    }

    /* Build the query */
    $query = "SELECT a.item_code,a.total,a.date FROM chart_values a, (SELECT DISTINCT item_code FROM chart_values GROUP BY item_code,date) b WHERE a.item_code = b.item_code";

    /* Loop through the results and build a JSON array for the data table */
    $result = $mysqli->query($query);

    $table = array();
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {

                if (!isset($table[$row['item_code']])) {
                    $table[$row['item_code']] = array(
                          'total' => array(),
                          'date' => array()
              );
           }

            $table[$row['item_code']]['total'][] = $row['total'];
            $table[$row['item_code']]['date'][] = $row['date'];
    }       
    echo var_dump($table);
    $datas = json_encode($table);

$datas = json_decode($datas,true);
// echo '<pre>';
// print_r($datas);

        $googleData = array('Date');
        foreach($datas as $key => $data){
            $googleData[] = $key;
        }

        for($i=0;$i<count($datas);$i++){
            foreach($datas as $key => $data){
                if(!in_array($data['date'][$i], $googleData)){
                    $googleData[] = $data['date'][$i];
                }
                $googleData[] = $data['total'][$i];
            }
        }

        $googleData = json_encode(array_chunk($googleData,count($datas)+1), JSON_NUMERIC_CHECK);
        // print_r($googleData);
?>



<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<body>
    <div style="width:90%; height:500px;" id="columnchart_material" style="width: 1000px; height: 500px;"></div>
</body>


<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

function drawChart() {

    var data = new google.visualization.arrayToDataTable(<?=$googleData?>);

    var options = {
        chart: {
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
        }
    };

    var chart = new google.visualization.ColumnChart(document.getElementById('columnchart_material'));

    chart.draw(data, options);
}
</script>
Hisham
  • 80
  • 11
  • Thank you Hisham for you input! I edited the script and ran it and het the echo of the variables (though quite some NULL) but the graph not rendering it seems. output: array(7) { ["Baxico"]=> array(2) { ["points"]=> array(6) { [0]=> string(2) "38" [1]=> string(2) "38" [2]=> string(1) "6" [3]=> string(2) "10" [4]=> string(2) "16" [5]=> string(2) "38" } ["CreatedTime"]=> array(6) { [0]=> NULL [1]=> NULL [2]=> NULL [3]=> NULL [4]=> NULL [5]=> NULL } } ["Degriek"]=> array(2) { ["points"]=> array(6) { [0]=> string(1) "1" [1]=> string(2) "16" ..... etc – Jorn May 16 '15 at 18:20
  • fixed the NULL values by date_format(CreatedTime, '%Y%m') and get nice output of the variables now but still no graph – Jorn May 16 '15 at 18:37
  • ok needed to make the dates unique, now it works perfectly! thanks alot! – Jorn May 16 '15 at 18:47