Google Pie Charts with PHP and MySQL

Populating pie charts with google api is one of the simplest way to do. here we are showing 
you a simple example to generate pie chart with real time data. fetching data from database table.
<?php
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";

$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, 
    $DatabasePassword, $DatabaseName);

if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$selectsql = "SELECT * FROM graph";
$result = mysqli_query($Connection, $selectsql);
?>

<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', 'Hours per Day'],
          <?php while($row = mysqli_fetch_array($result)){  ?>
             ["<?php echo $row['name']; ?>", <?php echo $row['count']; ?>],
          <?php } ?>
          ]);

         var options = {
           title: 'My Daily Activities'
            };

         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>
Run these queries in your database.
//Table structure for table `graph`
CREATE TABLE `graph` (
  `id` int(2) NOT NULL,
  `name` varchar(34) NOT NULL,
  `count` int(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

//Dumping data for table `graph`

INSERT INTO `graph` (`id`, `name`, `count`) VALUES
(1, 'Work', 11),
(2, 'Eat', 2),
(4, 'Commute', 2),
(5, 'Watch TV', 2),
(6, 'Sleep', 7);
Result:

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts