user1504583
user1504583

Reputation: 235

creating dynamic charts using google charts, mysql, and php

I need some help. I want to create a dynamic line chart using Google's chart api and data obtained via MySql. I'm using PHP to create the pages. I was able to create a simple chart with hard-coded values no problem. Now I am trying to use some MySql data instead, but with no luck. My webpage looks like this:

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

function drawChart() 
{
    var jsonData = $.ajax({
        url: "graphData.php",
        dataType:"json",
        async: false
}).responseText;

// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

var options = {'title':'Ticket Sales',
'width':500,
'height':400};

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options); 
}
</script>
<?
  PrintHeader($buf,$username,$userid,$session);

  echo("<div id='chart_div'></div>");
?>
</html>

Then my graphData.php page looks like this:

$sql = "SELECT MONTHNAME(DATE_SOLD), COUNT(*) FROM TICKET_SALES WHERE YEAR(DATE_SOLD) = 2012 GROUP BY MONTHNAME(DATE_SOLD) ORDER BY MONTH(DATE_SOLD);";

$result = mysql_query($sql, $conn) or die(mysql_error());

//start the json data in the format Google Chart js/API expects to recieve it
$JSONdata = "{
       \"cols\": [
           {\"label\":\"Month\",\"type\":\"string\"},
           {\"label\":\"Ticket Sales\",\"type\":\"number\"}
         ],
    \"rows\": [";

//loop through the db query result set and put into the chart cell values
while($row = mysql_fetch_row($result)) 
{
   $JSONdata .= "{\"c\":[{\"v\": " . $row[0] . "}, {\"v\": " . $row[1]  ."}]},";
}    

//end the json data/object literal with the correct syntax
$JSONdata .= "]}";

echo $JSONdata;
?>

When I load the page in my browser I just get a red box that says "Table has no columns." Can anyone tell me what I am doing wrong? Or perhaps a better/easier method? Any help would be greatly appreciated!!

Upvotes: 2

Views: 6961

Answers (2)

MM Developer
MM Developer

Reputation: 21

Yes, use the json_encode function. It will save you lots of headaches. I'd also make sure you run your numbers through an intval() or something.

My experience with the Google charts API is that if you send a number in quotes, the chart will fail to draw, so the data types in your PHP array must be correct so the json_encode result is correct in syntax.

Upvotes: 2

Orbling
Orbling

Reputation: 20602

Do not construct the JSON data that way, create a PHP array and use json_encode() to send the data back.

<?php

$sql = "SELECT MONTHNAME(DATE_SOLD), COUNT(*) FROM TICKET_SALES WHERE YEAR(DATE_SOLD) = 2012 GROUP BY MONTHNAME(DATE_SOLD) ORDER BY MONTH(DATE_SOLD);";

$result = mysql_query($sql, $conn) or die(mysql_error());

//start the json data in the format Google Chart js/API expects to recieve it
$data = array('cols' => array(array('label' => 'Month', 'type' => 'string'),
                              array('label' => 'Ticket Sales', 'type' => 'string')),
              'rows' => array());

while($row = mysql_fetch_row($result)) {
   $data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}    

echo json_encode($data);

I have not checked the JSON output is what is wanted, only made it the same as what you were trying to generate. Also, you should get the die() to return an invalid state in a JSON object, so you can tell it failed.

Upvotes: 2

Related Questions