Cyrus Bitangcol
Share This
Scroll Down
Categories
//CREATING DYNAMIC PIE CHART IN PHP

CREATING DYNAMIC PIE CHART IN PHP

CREATING DYNAMIC PIE CHART IN PHP

Today I want to share and show how to create a dynamic pie chart using Php, JavaScript, and MySQL, I saw dynamic because the data the will shown in the pie chart were pulled from a database MySQL.

You can also create other types of a chart such as a bar chart, line graph and any other type of chart, but in this tutorial, we will cover up a pie chart that will give you a good idea on how to create a JavaScript pie chart connected to MySQL.

 

Database for Dynamic Pie Chart


— Table structure for table `affiliate`

CREATE TABLE `affiliate` (
`id` int(11) NOT NULL,
`name` varchar(32) NOT NULL,
`ratings` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


— Dumping data for table `affiliate`

INSERT INTO `affiliate` (`id`, `name`, `ratings`) VALUES
(1, ‘Leads’, 20),
(2, ‘Revenue’, 10),
(3, ‘Clicks’, 100);

LibChart to create Dynamic Charts image (PHP)

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Pie Chart Demo (LibChart)- http://codeninja.cyrusbitangcol.com/</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-15″ />
</head>
<body>
<?php
//include the library
include “libchart/libchart/classes/libchart.php”;

//new pie chart instance
$chart = new PieChart( 500, 300 );

//data set instance
$dataSet = new XYDataSet();

//actual data
//get data from the database

//include database connection
include ‘db_connect.php’;

//query all records from the database
$query = “select * from affiliate”;

//execute the query
$result = $mysqli->query( $query );

//get number of rows returned
$num_results = $result->num_rows;

if( $num_results > 0){

while( $row = $result->fetch_assoc() ){
extract($row);
$dataSet->addPoint(new Point(“{$name} {$ratings})”, $ratings));
}

//finalize dataset
$chart->setDataSet($dataSet);

//set chart title
$chart->setTitle(“Statistic for June 2012”);

//render as an image and store under “generated” folder
$chart->render(“generated/1.png”);

//pull the generated chart where it was stored
echo “<img alt=’Pie chart’ src=’generated/1.png’ style=’border: 1px solid gray;’/>”;

}else{
echo “No statistic found in the database.”;
}
?>
</body>
</html>

For the full code download the file on http://codeninja.cyrusbitangcol.com

File password: “dynamicpiechart”

  • 0 Comment
Get in Touch
Close