How to graphically represent my database (mysql phpmyadmin) - php

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.

Related

Google chart show visualization out of form input

I am actually working on a project to visualize measurement values. Right know I had the ability to visualize all the values from the database, but going further to make it possible to use checkbox so it will be easier to choose what the user want to see. I am stuck how to make it possible for the user to firstly use checkbox, one solution was to make many if for each of the checkbox and them together if one or more as checked.
Things i need help with:
Giving the user opportunity to choose what they want to see out of the checkbox.
Sort data out of date and time.
This is the goal:
So far have I came:
Code:
<?php
$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("chart", $con);
$sth = mysql_query("SELECT * FROM googlechart");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Time', 'type' => 'number'),
array('label' => 'PH', 'type' => 'number'),
array('label' => 'temperature','type' => 'number'),
array('label' => 'Chlorine','type' => 'number') );
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Time']);
$temp[] = array('v' => (string) $r['PH']);
$temp[] = array('v' => (string) $r['temperature']);
$temp[] = array('v' => (string) $r['Chlorine']);
$temp[] = array('v' => (int) $r['Time']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<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(<?=$jsonTable?>);
var options = {
/*width: 900, height: 900, */
title: 'Visualization',
/* curveType: 'function', */
legend: { position: 'bottom' },
pointSize: 10,
vAxis: {title: "Values", titleTextStyle: {italic: false}},
hAxis: {title: "Time", titleTextStyle: {italic: false}},
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Phpmyadmin:
You can always sanitize your DataTable by using removeColumn. You dont have a fiddle nor give example of the JSON, so here is an example with some other values - but the technique is very simple.
Suppose you have 3 rows with data : Cats, blanket1 and blanket2. Then implement checkboxes for each data column :
<input type="checkbox" id="cats" checked="checked">
<label for="cats">cats</label>
<input type="checkbox" id="blanket1" checked="checked">
<label for="blanket1">blanket2</label>
...
In your drawChart method, examine the checked state for each checkbox and remove the corresponding data column if it is not :
//remember reverse order!
if (!blanket2.checked) data.removeColumn(3);
if (!blanket1.checked) data.removeColumn(2)
...
Reverse order is nessecary, you have to check for the last column first, then the second last column and so on.
Finally, assign a click handler to each checkbox, redrawing the chart each time a checkbox is clicked :
cats.onchange = drawChart;
blanket1.onchange = drawChart;
...
See demo -> http://jsfiddle.net/rJHtA/
Off course - in your case I would not ruin the original <?=$jsonTable?> each and every time. Hold the original <?=$jsonTable?> in a global variable and create the chart out of a local copy of that.
To order data by date (time) you must reload the page or use AJAX to get a new <?=$jsonTable?>. This should not be done along with the show / hide of the columns (no need to reload data you allready have). It is impossible to deliver a concrete example since you are not telling how the dates are inputted in the (supposed) form, how you intend to process the PHP or even what format time has in the table. Is it strings? We dont know. But assuming you have two <input>'s on a form, and Date is of type DATE :
<input type="text" name="from">
<input type="text" name="to">
Then on the server :
$SQL = 'SELECT * FROM googlechart '.
'WHERE `Date` BETWEEN "'.$_GET['from'].'" AND "'.$_GET['to'].'"';
$sth = mysql_query($SQL);

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.

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

Categories