Create Dynamic Google Pie Chart in PHP and MySQL

Hey Technoz, In this tutorial we are going to learn how to create dynamic google pie chart in php with additional feature of responsiveness. A pie chart presents data as a simple and easily understandable in picture. It can be an effective communication tool for visitors, because it represents data visually as a fractional part of a whole. Data comparison at a glance, enable user to make an immediate analysis or to understand information quickly. In this tutorial we are using google APi chart to improve simplicity and effectiveness of pie chart.

Creating database

To create dynamic google pie chart in php database need to create for storing the information about pie chart data

So lets create the database by using following queries. The following SQL creates piechart table which consist of  id, activity and time columns.

CREATE TABLE `piechart` (
  `id` int(255) NOT NULL,
  `activity` varchar(255) NOT NULL,
  `time` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Dumping data for table ‘piechart’

Now lets insert some records by using following query.

INSERT INTO `piechart` (`id`, `activity`, `time`) VALUES
(1, 'Hobbies', '3'),
(2, 'Coding', '8'),
(3, 'Class', '2'),
(4, 'TV', '1'),
(5, 'Fun', '2'),
(6, 'Sleep', '8');
COMMIT;

First, To make it convenient, We will create a new PHP file for database configuration named  dbconfig.php that holds all configured parameters:

<?php
$con = mysqli_connect("localhost","root","","technopoints");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

Create Dynamic Google Pie Chart in PHP

The following code piechart.php  is used to create dynamic google pie chart in PHP.

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<div class="container">
  <h2>Google Pie Chart | Technopoints</h2>
  <table class="table table-striped">
    <thead>
      <tr>
		<th>#</th>
        <th>Activities</th>
        <th>Hours</th>
      </tr>
    </thead>
    <tbody>
	<?php   require 'dbconfig.php';
		$fetchqry = "SELECT * FROM `piechart`";
		$result=mysqli_query($con,$fetchqry);
		$num=mysqli_num_rows($result);
	 while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ 
?>
      <tr>
		<td><?php echo $row['id'];?></td>
        <td><?php echo $row['activity'];?></td>
        <td><?php echo $row['time'];?></td>
      </tr>
	<?php } ?>
    </tbody>
  </table>
</div>
<div id="piechart"></div>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
  var data = google.visualization.arrayToDataTable([
  ['Hobbies', 'Time in Hours'], <?php
		$result=mysqli_query($con,$fetchqry);
  while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
  echo "['".$row['activity']."', ".$row['time']."],";
   } ?>  ]);
  // Optional; add a title and set the width and height of the chart
  var options = {'title':'Daily Activities', 
				 'width':'auto', 
				 'height':'auto',
				 // pieHole: 0.2,
				  };

  // Display the chart inside the <div> element with id="piechart"
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
}
</script>

</body>
</html>

 

Eventually this code fetch the data from the database and create a table first to understand which dynamic data consists in pie chart.

To make the pie chart responsive it is important to set the height and width to ‘auto‘ in the option.(This is the simplest trick you will find all over the internet brings by technopoints)

To create donut pie chart set piehole: value in the option. The pieHole option should be set to a number between 0 and 1.

To create 3D pie chart set the is3D option to true

Now, You can see the glimpse of the above code in following snapshot:

Create Dynamic Google Pie Chart in PHP

 

Finally we have learn how to Create Dynamic Google Pie Chart in PHP and MySQL.

If you have any doubts regarding to this tutorial feel free to ask in the comment section below.

To catch even more knowledgeable and easy understandable tutorials please subscribe to get email notification.

Download Source Code

1 thought on “Create Dynamic Google Pie Chart in PHP and MySQL

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.