CanvasJS provides a very developer friendly chat or graph library. The library is based on HTML 5 and JS. And can also be used for displaying realtime charts or graphs also.
There are various types of charts/graphs available.
Below are some useful codes
Frontend code:
<?php
$conn = mysql_connect("localhost","xxxxxxxxx","xxxxxxxxx");
if(!$conn)
{
echo "Error: failed to connect DB Server";
die();
}
if(!mysql_select_db("xxxxxxxxx",$conn))
{
echo "Error: failed to connect DB";
die();
}
$jsonArray1 = array();
$i=0;
$result = mysql_query("select * from weather_log");
while($rows = mysql_fetch_array($result))
{
$jsonArray1[$i] = array(date("Y,m,d,H,i",$rows['timestamp']), floatval($rows['temperature']));
}
?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var chart;
window.onload = function () {
chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Temperature"
},
data: [
{
type: "line",
dataPoints: [
<?php
for($j=0;$j<$i;$j++)
{
?>
{ x: new Date(<?php echo $jsonArray1[$j][0] ?>), y: <?php echo $jsonArray1[$j][1] ?> } <?php echo $j<$i-1?"," :"" ?>
<?php
}
?>
]
}
]
});
chart.render();
}
function updateTemp()
{
var str = JSON.parse(updateData("t"));
var date = str[1].split(",");
chart.options.data[0].dataPoints.push({x : new Date(date[0],date[1],date[2],date[3],date[4]), y : parseFloat(str[0]) });
chart.render();
};
function updateData(type)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "dataPlotter.php?q=" + type, false);
xmlhttp.send();
return xmlhttp.responseText;
}
setInterval("updateTemp()",360000);
</script>
</head>
<body>
<!--Div that will hold the chart-->
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="canvasjs.min.js"></script>
<script src="jquery.canvasjs.min.js"></script>
</body>
</html>
Backend code (dataPlotter.php in above snippet)
$result = mysql_query("select temperature,timestamp from weather_log order by timestamp desc limit 0,1");
$rows = mysql_fetch_array($result);
header('Content-Type: application/json');
echo json_encode(array($rows['temperature'],date("Y,m,d,H,i",$rows['timestamp'])));