Using PHP with charts and MySQL data - php

I'm using google charts to output a very simple pie chart
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Games', 'Number'],
['Win', 11],
['Lose', 2]
]);
var options = {
title: 'Win/Lose Ratio'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
However, in place of the values for Win and Lose, I want to pull 2 numbers out of my database. This doesn't need any kind of loop, just a way to reference 2 specific fields on a row instead of the values 11 and 2. This is the SQL query I'm using to get those two values
$qry =("SELECT games_won, games_lost FROM Members where member_id = '".$_SESSION['SESS_MEMBER_ID']."'");
$result = mysql_query($qry);
$row = mysql_fetch_array($result);
$won = $row[games_won];
$lost = $row[games_lost];
Does anyone know how to do this?
I've had a look at a lot of other FAQ's on the subject but they all deal with a collection of values in the same field and looping through severals rows of data, as opposed to referencing specific entries in the database.
Thanks in advance!

Have you tried this:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Games', 'Number'],
['Win', <?php echo($won); ?>],
['Lose', <?php echo($lost); ?>]
]);
var options = {
title: 'Win/Lose Ratio'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
All you are doing is grabbing the values, then echoing them out into your JavaScript. Please do note that I am not error checking, that is something you will need to think about when directly injecting values into HTML or JavaScript!
A better way of doing this is writing your code as a RESTful API. Have your SQL code in a place that you can send a member_id as a GET request. That, in turn, can print out the games won/lost inside JSON. Than, you can preform an AJAX request and grab those values to populate your table (just reference the values inside the returned JSON as regular JavaScript variables).

Related

Getting values from input for Google Charts

I have a page listing in table format some sales data. I want to include a chart. Since I already have to retrieve the data for the table I figured I would also build the array for google and put it in a hidden input to retrieve it with javascript. So this is the javascript
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var chartD = document.getElementById('chartD').value;
var data = google.visualization.arrayToDataTable([chartD]);
var options = {'title':'Sales'};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
This is the input I get the data from
<input type="hidden" id="chartD" value="['Date', 'Units Sold'],
['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00],
['03-08', 19.00], ['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]">
But when I run this I get an error Not a valid 2D array I then copied the value straight from the view page source like this
var data = google.visualization.arrayToDataTable([['Date', 'Units Sold'],
['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00], ['03-08', 19.00],
['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]]);
And that worked just fine. Does anyone have any idea what the problem is?
This is normal javascript functionality and nothing unique to Google or otherwise odd.
Take your HTML hidden div element and toss it in a document:
<input type="hidden" id="chartD" value="['Date', 'Units Sold'],
['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00],
['03-08', 19.00], ['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]">
Now test this javascript:
var chartD = document.getElementById('chartD').value;
var array = new Array(['Date', 'Units Sold'], ['03-01', 12.00], ['03-04', 32.00], ['03-06', 6.00], ['03-08', 19.00], ['03-11', 10.00], ['03-13', 5.00], ['03-15', 0]);
var array2 = new Array(chartD);
alert(array.length);
alert(array2.length);
This is the exact same behavior with standard javascript.
When you define the object with copy-paste, you get an array with 8 rows, 2 columns (hence length 8).
When you define the object with a string, you get an array that has one row and one column (containing a really long string).
Why would you expect Google to act any differently?
You either need to:
Pass in a fully formed 2D array to google
Pass in an array-defining string in by hand
This is all covered in the documentation.
Expecting Google to have some funky behavior different from javascript probably isn't the best approach.

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!!
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.
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.

Google Pie Charts and PHP

I would like to have a Google pie chart on my website. The pie chart would be filled with data from the database. I was loooking at some examples at https://developers.google.com/chart/interactive/docs/php_example, but I'm lost when it comes to the JSON format.
Here are some examples:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
And here is the snippet where I get lost (getData.php):
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("sampleData.json");
echo $string;
// Instead you can query your database and parse into JSON etc etc
?>
I have data stored in a database and not in JSON format. How do I work with the JSON format using MySQL database queries? If you have some examples or demos, I would appreciate it.
The first thing to do would be to have a look at the PHP manual about the json_encode() method. It provides examples on how to generate JSON with PHP.
Here is a short example from another similar SO question:
// Get your data from DB
$sth = mysql_query("SELECT ...");
// Create an array
$rows = array();
// Loop over the DB result and add it to your array
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
// Use json_encode() to turn the array into JSON
print json_encode($rows);
If you need to rename your database columns, so that your JSON-data get other names on the properties than those used in your DB, you can use AS in your SQL.
SELECT blog_title as title ...
just echo php result in
var data = new google.visualization.DataTable([<?php echo $result ;?>]);
u will get data from database as per as
below format
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
i think it's useful to u ,i am use same logic in heat map

how to work with dynamic data and google charts?

For example we have this line chart at Google Code API
there is a defined set of data which this chart reflects, however i want to create the chart using my own data from php/mysql scripting.
Here is the code provided by google to embed into html page..
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['imagelinechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Height');
data.addRows(3);
data.setCell(0, 0, 'Tong Ning mu');
data.setCell(1, 0, 'Huang Ang fa');
data.setCell(2, 0, 'Teng nu');
data.setCell(0, 1, 174);
data.setCell(1, 1, 523);
data.setCell(2, 1, 86);
// Create and draw the visualization.
new google.visualization.ImageLineChart(document.getElementById('visualization')).
draw(data, null);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 300px; height: 300px;"></div>
</body>
</html>
The option i have in my mind is to keep the following piece of code in a loop and generate the data. Does someone have something easy and efficient way to do this?
data.addColumn('string', 'Name');
data.addColumn('number', 'Height');
data.addRows(3);
data.setCell(0, 0, 'Tong Ning mu');
data.setCell(1, 0, 'Huang Ang fa');
data.setCell(2, 0, 'Teng nu');
data.setCell(0, 1, 174);
data.setCell(1, 1, 523);
data.setCell(2, 1, 86);
Your question touches on something that's frustrated me a lot: Google's API documentation isn't great! In particular, for Charts API, in basically all of their examples, the data for their chart is hard coded in the page, and, in real life, you'll basically always be rendering data stored in a DB and transmitted to the browser.
1) You need some code on the server (I use PHP) that queries the database, "prints" and transmits the JSON/complex data structure which is an object where the properties are arrays that contain additional objects with properties and values in the exact format that Google's Chart JavaScript expects to receive it in the browser. I did it like this:
$sql = "SELECT year,d_pop FROM metrics WHERE year IN ('1940','1950','1960','1970','1980')";
$sth = 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\":\"Year\",\"type\":\"string\"},
{\"label\":\"Detroit Population\",\"type\":\"number\"}
],
\"rows\": [";
//loop through the db query result set and put into the chart cell values
while($r = mysql_fetch_assoc($sth)) {
$JSONdata .= "{\"c\":[{\"v\": " . $r['year'] . "}, {\"v\": " . $r['d_pop'] ."}]},";
}
//end the json data/object literal with the correct syntax
$JSONdata .= "]}";
echo $JSONdata;
2) You need to receive that JSON object in your JavaScript on your page and pass it to Google's Chart JS. I brought in JQuery and then used it's AJAX method like this:
function drawChart() {
var jsonData = $.ajax({
url: "index_db.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {vAxis: {minValue: 0}});
}
My code snippets focus on the key parts of querying the mySQL DB, generating the JSON object Google Charts API needs, and receiving it with JQuery and AJAX. Hope this illuminates!
You can pass data as json instead making loop and passing with data.setCell()
At php side make your data json format. Using json_encode(). And on Api use this method to pass data. Check this link for more information
http://code.google.com/apis/chart/interactive/docs/reference.html#DataTable_toJSON

Google Area Chart

Im trying to using Google Area Chart and PHP to display some data. problem is i just cant get it to work. if anyone can help it will be most appriciated.
Here is my code:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'hits');
data.addRows([
<?php
$query = mysql_query("SELECT * FROM hits WHERE url='$url' GROUP BY date");
while ($row = mysql_fetch_array($query)){
$hits=mysql_num_rows($query);
$date=$row['date'];?>
['<?php echo "$date";?>', <?php echo ".$hits.";?>],
<?php } ?>
]);
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
hAxis: {title: 'Date', titleTextStyle: {color: '#FF0000'}}
});
}
</script>
<div id="chart_div"></div>
I would definitely suggest separating your PHP (server side) code from your JavaScript/html (client side) code.
The nice thing about the Google chart and graph APIs is there are several examples one can draw from, but it becomes much harder to reproduce something you're viewing when you embed PHP with MySQL queries within the blocks that contain your JavaScript and UI elements.
The following is a rough example of how you "might" go about dividing these things. In reality you would want your server side code (PHP in your case) in a totally separate file from your display/user interface code (HTML and JavaScript).
The 'DATE' and 'HITS' in the "Front end code" block are not actually variables or values, I'm simply indicating this is where you would input your values. Ideally you would pass the data from your MySQL query through the PHP server code to the JavaScript code, and then iterate through it there to build your graph. The passing things back and forth from PHP to JS can be done nicely using the JSON data interchange format. Both PHP and JavaScript (jQuery) have functions for encoding and decoding to/from JSON.
Front End Code:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'hits');
data.addRows(
['DATE', 'HITS']
);
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, title: 'Company Performance',
hAxis: {title: 'Date', titleTextStyle: {color: '#FF0000'}}
});
}
</script>
<div id="chart_div"></div>
Back End Code:
<?php
$query = mysql_query("SELECT * FROM hits WHERE url='$url' GROUP BY date");
$data_to_return = array();
while ($row = mysql_fetch_array($query))
{
$hits=mysql_num_rows($query);
$date=$row['date'];
$data_to_return[$date] = $hits; //building array of date=>hits data
}
$data_to_send_to_front_end = json_encode($data_to_return); //ridiculous variable name
?>

Categories