Tuesday, July 10, 2012

MySql php Graph


MySQL php Graph
Displaying data in graph we need to have graph library files which have been developed by the various developers.We could use these library files free in accordance with there usage policy.This tutorial I use PHPGraphLib -  PHP Graphing Library v2.30 which you have to download it from developers site and save it in your root folder where you store files of this tutorial.  click here to download it. 
                                                                              For this tutorial, I use the table progress1(MySQL ORDER BY MONTH) 


Car production in year-2012

Production
        Month

Following files were created
Graph.html
graph.php
phpgraphlib.php(downloaded from library)

Graph.html
<html>
<h3>Car production in year-2012</h3>
<table><tr>
<td valign="mid">Production</td><td><img src="graph.php" /></td></tr>
<tr><td colspan=2 align="center">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Month</b></td></tr>
</table>
</html>
graph.php
<?php
include("phpgraphlib.php");
$graph=new PHPGraphLib(430,350);
$link = mysql_connect('localhost','root', '', '')
   or die('Could not connect: ' . mysql_error());
  
mysql_select_db('my_database') or die('Could not select database');

$dataArray=array();


$sql="SELECT * FROM progress1";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
  while ($row = mysql_fetch_assoc($result)) {
      $month=$row["Month"];

if ($month == "1") {
$month_name = "January";
} else if ($month == "2"){
$month_name = "February";
} else if ($month == "3"){
$month_name = "March";
} else if ($month == "4"){
$month_name = "April";
}else if ($month == "5"){
$month_name = "May";
} else if ($month == "6"){
$month_name = "June";
} else if ($month == "7"){
$month_name = "July";
}else if ($month == "8"){
$month_name = "August";
} else if ($month == "9"){
$month_name = "September";
} else if ($month == "10"){
$month_name = "October";
}else if ($month == "11"){
$month_name = "November";
} else if ($month == "12"){
$month_name = "December";
}
      $Production=$row["Production"];
 
      $dataArray[$month_name]=$Production;
  }
}


$graph->addData($dataArray);
$graph->setTitle('car production in year-2012');
$graph->setBars(false);
$graph->setLine(true);
$graph->setDataPoints(true);
$graph->setDataPointColor('maroon');
$graph->setDataValues(true);
$graph->setDataValueColor('maroon');
$graph->setGoalLine(.0025);
$graph->setGoalLineColor('red');
$graph->createGraph();
?>

By changing above graph.php setBars(true),setLine(false) and setDataPoints(false),You could be obtained following bar graph instead of line graph.

Car production in year-2012

Production
        Month
 

No comments:

Post a Comment