creating dynamic charts using google charts, mysql, and php - 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.

Related

Data parsing from mysql into highchart with json

new to this and (nearly) desperated. What i want to do is the following:
read temp from sensor (works, returns float)
save data in mysql database boxklima.sensorid (works - table is boxklima.0414604605ff) in sets of date-temp pairs the date is stored as 2014-01-01 09:00:00 (datetime) and the temp as 12.123 (real)
graph data as x-axis: date y-axis: temp (totally messed this up)
So i stick to highcharts which looks nice and seems be easy to set up because everything happens client-side (except data-parsing).
Now I dont't know exactly how do create the array which is given to highchart. It should look something like this (content of create-graph.html)
<!DOCTYPE html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script‌​>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('data.php', function(data) {
options.series[0].data = temp;
var chart = new Highcharts.Chart(options);
});
});
</script>
Parse the data with the data.php (content shown below) from the sql-server, should generate the data on call, right?
<php>
$dbc = mysqli_connect("localhost", "pi", "pi", "boxklima");
$query = "SELECT date,temp FROM 0414604605ff";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$rows[$i]=array($row['date'],$row['temp']);
$i++;
}
echo json_encode($rows);
</php>
Opening (in browser) of data.php just shows
$dbc = mysqli_connect("localhost", "pi", "pi", "boxklima"); $query = "SELECT date,temp FROM 0414604605ff"; $data = mysqli_query($dbc, $query); $i=0; while($row = mysqli_fetch_array($data)) { $rows[$i]=array($row['date'],$row['temp']); $i++; } echo json_encode($rows);
Opening create-graph.html results in empty screen.
Credentials set to 755, the php-file has execution bit set, to. Files are in the same directory.
Help appreciated, thank you in advance, i'am lost in information and definitly puzzled.
Read through the other topics but since I'am new to this it gives me only little chunks which I was not able to match together. :S
Further information:
lighttpd/1.4.31
PHP Version 5.4.36-0+deb7u1
additional config files parsed
/etc/php5/cgi/conf.d/10-pdo.ini, /etc/php5/cgi/conf.d/20-gd.ini,
/etc/php5/cgi/conf.d/20-mcrypt.ini, /etc/php5/cgi/conf.d/20-mysql.ini,
/etc/php5/cgi/conf.d/20-mysqli.ini, /etc/php5/cgi/conf.d/20-pdo_mysql.ini
json support enabled
json version 1.2.1
mysql Client API version 5.5.40
Change your php file to this:
<?php
$dbc = mysqli_connect("localhost", "pi", "pi", "boxklima");
$query = "SELECT date,temp FROM 0414604605ff";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$rows[$i]=array($row['date'],$row['temp']);
$i++;
}
echo json_encode($rows);
?>
In create-graph.html, 'temp' variable is undefined.(You may open JavaScript Console and check for JavaScript errors)This is the reason why that page is blank.
Looking at your data.php file, I think the 'data' variable in callback function of $.getJSON would have structure like following:
[
[2014-01-01 09:00:00, 12.43]
[2014-01-02 09:00:00, 13.57]
]
Basically Array of Arrays.
So changing your function to this might help:
$.getJSON('data.php', function(data) {
dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[i][1]); // '1' index for getting that temp value. '0' for date.
}
options.series[0].data = dataTemp;
var chart = new Highcharts.Chart(options);
});
Also Please post the contents of data.php when you open it in web browser.
Also mention the JavaScript Console Error(if you get) when you open create-graph.html after making the changes.
You need to convert your string dates to timestamp and set datetime type of xAxis. To help, see strtotime function and apply in to your PHP script.

How to graphically represent my database (mysql phpmyadmin)

I would like to take student's exam results and represent it as a chart for student's supervisor.
So I will fetch the database information (which is student's result and represent it graphically to the supervisor to notice student's progress)
I have been looking for a way to represent that either by php coding or js but I couldn't.
I found google API that drawing charts in a very nice way but it accepts only JSON tables...
Thank you
If you are working with a PHP backend, you can query the database to get a result set and put that result set into a format the Google Visualization API can understand, then draw charts based on it. There is no need to export the data every time you need to draw a chart:
<?php
$username = 'mysqlusername';
$password = 'password';
$databasename = 'school';
try {
$db = new PDO("mysql:dbname=$databasename", $username, $password);
}
catch (PDOException $e) {
die ($e->getMessage());
}
$query = $db-> prepare('SELECT student, grade FROM myClass WHERE year = :year AND semester = :semester');
// 'year' and 'semester' here get substituted into the query for ':year' and ':semester' respectively
// this is a secure way of passing in parameters to the query so that a malicious user cannot use SQL injection to penetrate your security
$query->execute(array('year' => 2013, 'semester' => 1));
$results = $query->fetchAll(PDO::FETCH_ASSOC);
$data = array(
// create whatever columns are necessary for your charts here
'cols' => array(
array('type' => 'string', 'label' => 'Student Name'),
array('type' => 'number', 'label' => 'Grade')
)
'rows' => array()
);
foreach ($results as $row) {
// 'student' and 'grade' here refer to the column names in the SQL query
$data['rows'][] = array('c' => array(
array('v' => $row['student']),
array('v' => $row['grade'])
});
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function drawChart() {
var data = new google.visualization.DataTable(<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>);
var chart = new google.visualization.ColumnChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 400,
width: 600
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
Just use the export function in phpmyadmin (here you can find which formats are supported). Select the EXPORT button in the top of the page (of the table you'd like to export) and then change the format from SQL to JSON.
If you want to export data automatically (don't tag phpmyadmin), you should just excract them from the database and then encode them in json format (json_encode()). Then just take them to Google API and retrieve the charts.
If the phpMyAdmin charting features are not advanced enough, and you don't need a web-interface, you could also use Excel PowerPivot to connect to your MySQL (or any other) database.
There is a very good HOWTO on setting up the link here:
http://www.joyofdata.de/blog/how-to-set-up-powerpivot-and-make-it-talk-to-mysql/
phpMyAdmin (version 3.4.0) can generate simple charts, see https://docs.phpmyadmin.net/en/latest/charts.html.

Using PHP with charts and MySQL data

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

How to plot real time graph using php and AJAX?

I am a newbie in web development. I have just started programming in php. I want to develop a dynamic page that is connected to MySQL database (from a server) and display the result in a plot (could be scatter, histogram) in real time. So far I managed to get my data from my database and display the graph. However, I couldn't manage to do it in real time.
I have been searching around. What I found was using AJAX to do the real time plot. Fine, I did some tutorial on it and was able to run the examples. My challenge is to plot the graph.
If it helps, this is exactly what I want to do
http://jsxgraph.uni-bayreuth.de/wiki/index.php/Real-time_graphing
I have tried to run this code but I was not able to.
Could anyone give me how to start from simple? I will elaborate if my question is not clear enough.
Thank you in advance!
#Tim, here is what I tried to do.
My php is
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
//echo "Database Connected!";
mysql_select_db("DB", $con);
$sql=mysql_query("SELECT Def_ID, Def_BH FROM BBB WHERE Ln_Def < 1200");
$Def_ID= array();
$Def_BH = array();
while($rs = mysql_fetch_array($sql))
{
$Def_ID[] = $rs['Def_ID'];
$Def_BH [] = $rs['Def_BH '];
}
mysql_close($con);
$json = array(
'Def_ID' => $Def_ID,
'Def_BH' => $Def_BH
);
echo json_encode($json);
?>
The output is
{"Df_ID":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41"],"Df_BH":["1","1","1","5","5","2","1","1","1","1","2","1","1","1","1","1","1","1","1","1","1","1","2","1","1","2","1","3","10","1","2","1","1","1","2","2","2","1","1","1","1","1"]}
Then my script follows
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Example: Real-time updates</title>
<link href="../examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language = "javascript" type="text/javascript" src="Include/excanvas.js"></script>
</head>
<body>
<div id="placeholder" style="width:600px;height:300px"></div>
</body>
<script type="text/javascript">
function doRequest(e) {
var url = 'fakesensor.php'; // the PHP file
$.getJSON(url,data,requestCallback); // send request
}
function requestCallback(data, textStatus, xhr) {
// // you can do stuff with "value" here
$.each(data, function(index, value) {
console.log(value.Df_ID);
console.log(value.Df_BH);
});
}
</script>
</html>
I would like to plot Def_Id versus Def_BH. Do you see what have gone wrong?
Look at High Charts Dynamic Update ;-)
First, you need to get the output right. In my opinion, JSON is the best format to transfer data between server and client using async requests. It's a data format that can be parsed easily by a lot of programming languages.
Next, you need to figure out what you are going to transfer. Are you going to transfer a bulk of data at once and animate it using javascript, or are you planning to send a request per new bit?
My advice: make the amount of requests as little as possible. Requests are slow.
How do you know what to send? Are you going a timestamp? An ID? Anything is possible. Because ID's auto-increment, you might as well use that.
So first, I'm going to set up my PHP:
// get user input
$lastID = intval($_GET['lastid']);
// --------------------------------
// FETCH RECORDS FROM DATABASE HERE
// --------------------------------
// $sql = "SELECT * FROM `graph` WHERE `id` > " . $lastID;
// CREATE DUMMY CONTENT
$data = array();
for($i = $lastID; $i < $lastID + 50; $i++) {
array_push($data, array(
'id' => $i,
'position' => array(
'x' => $i,
'y' => mt_rand(0, 10) // random value between 0 and 10
)
));
}
// END CREATING DUMMY CONTENT
// create response
$json = array(
'lastID' => $data[count($data) - 1]['id'],
'data' => $data
);
// display response
echo json_encode($json);
As you can see, I'm getting a bulk of data using lastid as input. That input is important.
Now, we are going to set up our javascript to get the request. I'm using the jQuery library for my AJAX requests because I'm a jQuery fanboy!
var interval = setInterval(doRequest, 4000); // run "doRequest" every 4000ms
var lastID = 0; // set 0 as default to ensure we get the data from the start
function doRequest(e) {
var url = 'my-file.php'; // the PHP file
var data = {'lastid': lastID}; // input for the PHP file
$.getJSON(url, data, requestCallback); // send request
}
// this function is run when $.getJSON() is completed
function requestCallback(data, textStatus, xhr) {
lastID = data.lastID; // save lastID
// loop through data
$.each(data, function(index, value) {
// you can do stuff with "value" here
console.log(value.id); // display ID
console.log(value.position.x); // display X
console.log(value.position.y); // display Y
});
}
All that remains is outputting the results to a graph!
When you look at your PHP response you'll see that there's one object with two properties containing an array.
{
"Df_ID": [1, 2, 3, ...],
"Df_BH": [1, 2, 3, ...]
}
You can access these properties by... calling those properties data.Df_ID, data.Df_BH
function requestCallback(data, textStatus, xhr) {
console.log(data.Df_ID, data.Df_BH);
}
These are what i found in google -
http://www.makeuseof.com/tag/add-graphs-php-web-app-pchart/
http://www.ebrueggeman.com/phpgraphlib
You could create dynamic graphs and call using AJAX infinitely.

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

Categories