Monday, July 5, 2021

How to create PIE Chart in PHP dynamic with Google chart API PHP

Step 1. Make a PHP file to display data in pie chart

We make a PHP file and save it with a name piechart.php
Click to link -: DOWNLOAD HTML PIA CHART

Step 2. Make the DATABASE And Create the table 





CODE:-
<?php
try{
  $con = new PDO("mysql:host=localhost;dbname=test","root","");
}catch(PDOExection $e) {
  echo $e->getMessage();
}

$sql = "SELECT COUNT(gender) as tcount,gender FROM data GROUP BY gender";
$smtp = $con->prepare($sql);
$smtp->execute();
$arr = $smtp->fetchAll(PDO::FETCH_ASSOC);
echo"<pre>";
echo print_r($arr);
?>
<html>
  <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([
          ['Task', 'Count'],
          <?php foreach ($arr as $key => $value) {?>
            ['<?php echo $value['gender']?>', <?php echo $value['tcount']?>],
          <?php }?>
        ]);

        var options = {
          title: 'Gender Count'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

JSON Formate To Display Data In Pie Chart It Takes Only One Step:-



<?php

$rating_data = array(
array('Employee', 'Rating'),
array('Suresh',25),
array('Amit',56),
array('Rahul',37),
array('Lucky',71),
array('Pooja',11),
array('Manoj',49)
);

$encoded_data = json_encode($rating_data);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() 
{
var data = google.visualization.arrayToDataTable(
<?php  echo $encoded_data; ?>
);
var options = {
title: "Employee Ratings"
};
var chart = new google.visualization.PieChart(document.getElementById("employee_piechart"));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="employee_piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>

No comments:

Post a Comment

If you have any problem please let me know.