Making a graph in php, mysql with highcharts - javascript

I need make a graph in highcharts, but I need to get the values from mysql until now I only can add the timestamp value, but still left the other value to the Y graph, Im new in all this I hope you can give some help, the other value I need to use is a int value.
I'm still trying to add the second value, but with this only value (hour) shows me nothing.
The homework is to make a graph with values in function of time
<HTML>
<head>
<!-- Importa las librerias de jQuery y las de Highcharts -->
<script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<?php
$conexion = mysql_connect('localhost','root' , '') or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db('fancysensorsdb', $conexion);
$query = "SELECT hora FROM temperatura";
$registros = mysql_query($query) or die(mysql_error());
while ($datos = mysql_fetch_array($registros))
{
extract ($datos);
$datetime *= 1000; // Convertir hora Unix a JavaScript
$data[] = "[$datetime, $hora]";
}
$query = "SELECT valor FROM temperatura";
$registros = mysql_query($query) or die(mysql_error());
while ($valores = mysql_fetch_array($registros))
{
extract ($valores);
$datos[] = $valores;
}
?>
<script type="text/javascript">
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [<?php echo join($data, ',') ?>]
}]
});
</script>
<div id="container" style="width: 100%; height: 500px; margin: 0 auto"></div>
</body>
</html>

Basically you are passing variable data from PHP to javaScript. Based on your code, it won't work. Please take a look at this post.

Related

unable to generate pie chart from phpmyadmin

i want to create google pie chart with help of getting table from database ...but till now i did not get output ...i have searched several websites..but i did not clarify anything...please check my code and tell
<?php
mysql_connect('localhost','root','');
mysql_select_db('chart');
$sqlquery1="select * from pie_chart";
$sqlresult1=mysql_query($sqlquery1);
$rows=array();
while($r=mysql_fetch_assoc($sqlresult1))
{
$rows[]=$r;
}
$data= json_encode($rows);
?>
<html>
<head>
<!--Load the AJAX API -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></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 data = new google.visualization.DataTable();
data.addColumn("string", "Quarter");
data.addColumn("number", "Number");
data.addRows(<?php echo $data ?>);
]);
//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>
<?php
/* Establish the database connection */
$mysql =mysqli_connect('localhost', 'root', '', 'chart');
/* select all the tasks from the table piechart */
$result = $mysql->query('SELECT * FROM piechart');
/*
---------------------------
example data: Table (piechart)
--------------------------
Task percent
job 30
daily 20
working 35
sleep 15
*/
$rows = array();
$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 Slice title
*/
array('label' => 'task', 'type' => 'string'),
array('label' => 'percent', 'type' => 'number')
);
/* Extract the information from $result */
/* associate array are used in above ,so we used foreach loop*/
foreach($result as $r)
{
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['task']);
// Values of the each slice
$temp[] = array('v' => (int) $r['percent']);
//rows of side title
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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);
// Load the Visualization API and the piechart package.
function drawChart()
{
// Create our data table out of JSON data loaded from server.
var bar_chart_data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
title: 'Daily Work log',
is3D: 'true',//3D effect true
width: 900,
height: 500
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(bar_chart_data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div" ></div>
</body>
</html>
</script>
</head>

Loading data to Highchart from MySQL and displaying in appropriate way

I am facing the problem with highchart. I've been looking for solution for 2 days without result.
live-data.php
<?php
header("Content-type: text/json");
include("./dbSettings.php");
$result = $conn->query("SELECT current_ts, heartRate FROM data WHERE id='1234'");
if (!$result) {
die(mysqli_error($conn));
}
$ret = array();
while ($row = mysqli_fetch_array($result)){
$current_time = strtotime($row['current_ts'])*1000;
$heartRate = intval($row['heartRate']);
$y = rand(0, 100);
$ret[] = array($current_time, $heartRate);
}
echo json_encode($ret, JSON_NUMERIC_CHECK);
?>
output from live-data.php
[[1463404815000,131],[1463404926000,108],[1463404927000,180],[1463404928000,160],[1463404967000,143],[1463404968000,105],[1463404969000,107],[1463404976000,100],[1463404977000,123],[1463867458000,108],[1463867459000,113],[1463867460000,108],[1463867494000,97],[1463867495000,158],[1463867496000,74]]
index.html (it's totally wrong, but I attach it)
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script data-require="highcharts#*" data-semver="4.0.1" src="//cdnjs.cloudflare.com/ajax/libs/highcharts/4.0.1/highcharts.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('live-data.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
I would like to make my chart looking like this one below, but a bit more detailed. I will retrieve data from my database every minute. Chart will be updated after manually refresh, but in the future I will make it dynamically (using ajax). It will be great if I could show data in appropriate way (i.e. April 7, 2016, 15:12:38)
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/basic-line/
I hope someone can help me on my way.
Thanks,
Paul
I've assumed you are talking about tooltip dates because on Axis your label will be too long.
You need to play with dateTimeLabelFormats. See my example:
http://jsfiddle.net/qq5rqazj/2/

HighCharts and PHP json_encode. Data from MySQL. No data on chart

Trying to produce HighCharts with data from MySQL. Parsing data from MySQL using PHP and the json_encode function. Problem: No data on chart.
This is my javascript:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('json.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="max-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
This is my json.php:
<?php
$host = "localhost:3306";
$user = "removed";
$pass = "removed";
$dbname = "removed";
$connection = mysqli_connect($host, $user, $pass, $dbname);
$query = "SELECT temp, time from vejr where time > '2016-04-25 06:14:23'";
$result = mysqli_query($connection, $query);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
?>
This is the output from the json.php:
[{"temp":"1.6","time":"2016-04-25 08:14:23"}, {"temp":"2.6","time":"2016-04-25 09:14:23"},{"temp":"3.6","time":"2016-04-25 10:14:23"},{"temp":"4.6","time":"2016-04-25 11:14:23"}, {"temp":"5.6","time":"2016-04-25 12:14:23"},{"temp":"6.6","time":"2016-04-25 13:14:23"},{"temp":"7.6","time":"2016-04-25 14:14:23"},{"temp":"8.6","time":"2016-04-25 15:14:23"}]
What I'm trying to do is a chart with time (fx 2016-04-25 08:14:23) on the x-axis, and the value (fx 1.6) on the y-axis.
Got inspiration from this: http://www.highcharts.com/docs/working-with-data/custom-preprocessing#3
And also, I know that my timestamp on the x-axis is not perfect, it is long (2016-04-25 08:14:23), but that is what my feeding-software currently is sending to my MySQL. What would be perfect?
Kind Regards
The issue is caused by 3 reasons.
Values should be named like x and y, not custom fields
The y value should be number, not string like you have (use the JSON_NUMERIC_CHECK flag in json_encode)
The x value, should be timestamp (time in miliseconds). In PHP you can use strtotime() function

CanvasJs dynamic Data with PHP, mySQL

screen shoot
Hello i have obstacle for my chart from CanvasJs.
I just put simple code to get simple chart with parameter target and actual, i found error in dataPoints: i think the problem just wrong statements.
this my error code:
dataPoints: [
<?PHP $mkmi3= mysql_query("SELECT * FROM monthkpimontindv WHERE idKpiDetIndv='$q'");
While ($mkmi4= mysql_fetch_assoc($mkmi3))
{
echo "{ label: ".$mkmi4['period'].", y: ".$mkmi4['actual']." },\n";
}
?>
]
Here is how we can display MySQL data in CanvasJS, Try like this.
Here, Create a PHP service that returns data in JSON format. HTML page that does AJAX request to the server and fetches the data. After getting the data, it renders a Chart.
PHP Service to return JSON Data
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","user","password","canvasjssampledb");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM sales");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['product'] , "y" => $row['total_sales']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
HTML Page to Fetch Data and render Chart
!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Note:: IE8- is supported in v1.3 and above.

Google pie chart single value from table

I have a problem to display a pie chart.
i have this code:
<?php
$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("oes", $con);
// The Chart table contains two fields: weekly_task and percentage
// This example will display a pie chart. If you need other charts such as a Bar chart,
// you will need to modify the code a little to make it work with bar chart and other charts
$sth = mysql_query("select t.testname as Test,t.testdesc as `Tip test`,
DATE_FORMAT(st.starttime,'%d %M %Y ') as Data,
sub.subname as Disciplina,sub.subdesc as Profesor,sub.an as `Anul de studii`,
(SELECT sum(q.marks) from studentquestion as sq,
question as q where sq.testid=q.testid and sq.qnid=q.qnid and sq.answered='answered'
and sq.stdanswer=q.correctanswer and
sq.stdid='" . htmlspecialchars($_SESSION['stdid'],ENT_QUOTES) . "' and
sq.testid=t.testid) as Nota,(SELECT sum(q.marks)
from studentquestion as sq, question as q where sq.testid=q.testid
and sq.qnid=q.qnid and
sq.stdid='" . htmlspecialchars($_SESSION['stdid'],ENT_QUOTES) . "'
and sq.testid=t.testid) as NotaMaxima
from studenttest as st,test as t,subject as sub,student as ss where
t.testid=st.testid and st.stdid=".$_SESSION['stdid']."
and st.status='over' and sub.subid=t.subid and ss.stdid=".$_SESSION['stdid']."
order by t.testid DESC LIMIT 1 ;");
$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' => 'Test', 'type' => 'string'),
array('label' => 'Nota', 'type' => 'number'),
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['Test']);
// Values of each slice
$temp[] = array('v' => (float) (($r['Nota']/$r['NotaMaxima'])*100) );
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../../stil/stil.css"/>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Procentaj de raspuns',
is3D: 'true',
backgroundColor: "transparent",
width: 500,
height: 300,
max:10,
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<br><br><br><br><br><br><div id="chart_div" style="padding-left: 240px; align:center;"></div></>
</body>
</html>
I want to display this value: http://i.stack.imgur.com/1a2zm.png
Not like this: http://i.stack.imgur.com/bVcJE.png
But like real percentage. Ex: 54% one color and the rest other color. I dont know how to do it because is a single value.
In sql select the value is " NotaMaxima "
And how do i use $rows for 2 things like Nota and NotaMaxima?
U can add by your self another value (other).
If $result array:
Ex. if(count($result)==1) then $anotherVal = 100-$result[0] and add to $result[1]=$anotherVal.
And add to chart data two values.

Categories

Resources