How to Create a Simple Bar Chart using Google Charts API

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 bar 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 database.

Creating the Presentation

Lastly, we create the page where we present the data using bar 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', '', 'database');
  4. ?>
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <meta charset="utf-8">
  9. <title>How to Create a Simple Bar Chart using Google Charts API</title>
  10. </head>
  11. <body>
  12. <div id="barchart" style="width: 900px; height: 500px;"></div>
  13.  
  14. <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  15. <script type="text/javascript">
  16. google.charts.load('current', {'packages':['bar']});
  17. google.charts.setOnLoadCallback(drawChart);
  18.  
  19. function drawChart(){
  20. var data = google.visualization.arrayToDataTable([
  21. ['Year', 'Sales', 'Expenses', 'Profit'],
  22. <?php
  23. for($i = 2014; $i <= 2017; $i++){
  24. //sales
  25. $sql = "SELECT sum(sales) AS sum_sales FROM sales WHERE year(date) = '$i'";
  26. $sales_query = $conn->query($sql);
  27. $sales_row = $sales_query->fetch_assoc();
  28. //expense
  29. $sql = "SELECT sum(expenses) AS sum_expenses FROM expenses WHERE year(date) = '$i'";
  30. $expense_query = $conn->query($sql);
  31. $expense_row = $expense_query->fetch_assoc();
  32. //profit
  33. $profit = $sales_row['sum_sales'] - $expense_row['sum_expenses'];
  34. //displaying the needed data
  35. echo '["'.$i.'", '.$sales_row['sum_sales'].', '.$expense_row['sum_expenses'].', '.$profit.'],';
  36. }
  37. ?>
  38. ]);
  39.  
  40. var options = {
  41. chart: {
  42. title: 'Company Performance',
  43. subtitle: 'Sales, Expenses, and Profit: 2014-2017',
  44. }
  45. };
  46.  
  47. var chart = new google.charts.Bar(document.getElementById('barchart'));
  48.  
  49. chart.draw(data, google.charts.Bar.convertOptions(options));
  50.  
  51. }
  52. </script>
  53. </body>
  54. </html>
That ends this tutorial. Happy Coding :)

Add new comment