Create Dynamic Pie Chart in PHP with Google Charts

A pie chart is a circular graph which is divided into slices to represent numerical proportion. The pie chart mainly used to show comparison and the graphical representation helps understand the comparison easily. The pie chart is the perfect choice to illustrate data in a percentage format.

If you have a requirement to show the statistics of data with a pie chart, there is an easy way to create the pie chart in the web application. In this tutorial, we will show you how to create a dynamic pie chart with PHP and MySQL.

Google Visualization API provides an easy way to create charts on the website. Using Google charts API, you can generate pie chart to populate data from the database within minutes. Here we’ll create different types of pie charts to show dynamic data from the MySQL database using PHP and Google charts API. Also, this tutorial will help you to make Google pie chart dynamic with PHP and MySQL.

Making a Dynamic Pie Chart with PHP and MySQL

In our example pie chart script, we’ll show some programming languages on the pie chart. Also, the data will be retrieved from the MySQL database and their popularity will be shown on the pie chart.

Database Table Creation
To store the programming languages data a table needs to be created in the database. The following SQL creates a table named programming_languages in the MySQL database.

CREATE TABLE `programming_languages` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `rating` int(5) NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Dynamic Data on Google Pie Chart
At first dynamic data will be retrieved from the programming_languages table using PHP and MySQL. After that, the programming language names and ratings will be specified in the data variable.
In options variable, you can specify the desired title, width, and height of the pie chart.

<?php
// Database credentials
$dbHost 'localhost';
$dbUsername 'root';
$dbPassword 'root';
$dbName 'codexworld';

// Create connection and select db
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

// Get data from database
$result $db->query("SELECT name,rating FROM programming_languages WHERE status = '1' ORDER BY rating DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Language', 'Rating'],
      <?php
      
if($result->num_rows 0){
          while(
$row $result->fetch_assoc()){
            echo 
"['".$row['name']."', ".$row['rating']."],";
          }
      }
      
?> ]); var options = { title: 'Most Popular Programming Languages', width: 900, height: 500, }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> </head> <body> <!-- Display the pie chart --> <div id="piechart"></div> </body> </html>

You can make various types of pie charts with Google Charts API. Some popular types of the pie chart are given below.

Making a Dynamic 3D Pie Chart

Set is3D option to true to make a 3D pie chart.

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

function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Language', 'Rating'],
      <?php
      
if($result->num_rows 0){
          while(
$row $result->fetch_assoc()){
            echo 
"['".$row['name']."', ".$row['rating']."],";
          }
      }
      
?> ]); var options = { title: 'Most Popular Programming Languages', width: 900, height: 500, is3D: true, }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script>

Making a Dynamic Donut Pie Chart

Donut Chart is same like the normal pie chart with a hole in the center. Set pieHole option to make a Donut Pie Chart.

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

function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Language', 'Rating'],
      <?php
      
if($result->num_rows 0){
          while(
$row $result->fetch_assoc()){
            echo 
"['".$row['name']."', ".$row['rating']."],";
          }
      }
      
?> ]); var options = { title: 'Most Popular Programming Languages', width: 900, height: 500, pieHole: 0.5, }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script>

Making a Dynamic Slice Exploding Pie Chart

To separate slices from the rest of the pie chart, use offset property of the slices option.

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

function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Language', 'Rating'],
      <?php
      
if($result->num_rows 0){
          while(
$row $result->fetch_assoc()){
            echo 
"['".$row['name']."', ".$row['rating']."],";
          }
      }
      
?> ]); var options = { title: 'Most Popular Programming Languages', width: 900, height: 500, pieSliceText: 'label', slices: { 0: {offset: 0.5}, 6: {offset: 0.4}, 8: {offset: 0.3} }, }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script>

Conclusion

In this dynamic pie chart tutorial, we’ve shown the most used types of the pie charts. However, Google Charts provides various option to configure the pie chart. You can use those configuration options based on your requirement.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

1 Comment

  1. Itumeleng Said...

Leave a reply

keyboard_double_arrow_up