How to Create a Simple Pie Chart using Google Chart API with PHP/MySQLi

Creating our Database

First, we are going to create our database which contains the sample data that we are going to present using Google Chart API in the form of pie chart. I've included a .sql file in the downloadable of this tutorial which is a mysql database file. All you have to do is import the said file. If you have no idea on how to do this, please refer to my tutorial, How import .sql file to restore MySQL database. You should be able to create a database with tables named mydatabase.

Creating the Presentation

Lastly, we create the page where we present the data using pie chart. Create a new file, name it as index.php and paste the codes below.
  1. <?php
  2. //connection
  3. $conn = new mysqli('localhost', 'root', '', 'mydatabase');
  4.  
  5. $sql = "SELECT gender, count(*) as number FROM members GROUP BY gender";
  6. $query = $conn->query($sql);
  7.  
  8. ?>
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <meta charset="utf-8">
  13. <title>How to Create a Simple Pie Chart using Google Chart API using PHP/MySQLi</title>
  14. <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  15. </head>
  16. <body>
  17. <!-- this is where we show our chart -->
  18. <div id="piechart" style="width: 900px; height: 500px;"></div>
  19.  
  20. <!-- Load our Scripts -->
  21. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  22. <script type="text/javascript">
  23. google.charts.load('current', {'packages':['corechart']});
  24. google.charts.setOnLoadCallback(drawChart);
  25. function drawChart(){
  26. var data = google.visualization.arrayToDataTable([
  27. ['Gender', 'Number'],
  28. <?php
  29. while($row = $query->fetch_assoc()){
  30. echo "['".$row["gender"]."', ".$row["number"]."],";
  31. }
  32. ?>
  33. ]);
  34. var options = {
  35. title: 'Percentage of Male and Female Members',
  36. //is3D:true,
  37. pieHole: 0.4
  38. };
  39. var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  40. chart.draw(data, options);
  41. }
  42. </script>
  43. </body>
  44. </html>
That ends this tutorial. Happy Coding :)

Add new comment