Bar Chart using ChartJS, AngularJS and PHP/MySQLi

Getting Started

I've used CDN for Bootstrap, Angular JS and Chart JS so you need internet connection for them to work.

Creating our Database

First, we're going to create our MySQL Database where we fetch data to supply to our chart. 1. Open phpMyAdmin. 2. Click databases, create a database and name it as angular. 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
  1. CREATE TABLE `sales` (
  2. `saleid` int(11) NOT NULL AUTO_INCREMENT,
  3. `amount` double NOT NULL,
  4. `sale_date` datetime NOT NULL,
  5. PRIMARY KEY(`saleid`)
  1. INSERT INTO `sales` (`saleid`, `amount`, `sale_date`) VALUES
  2. (17, 50, '2018-01-01 16:00:00'),
  3. (18, 600, '2018-02-01 16:00:00'),
  4. (19, 50, '2018-02-04 16:00:00'),
  5. (20, 700, '2018-03-02 16:00:00'),
  6. (21, 350, '2018-04-03 16:00:00'),
  7. (22, 100, '2018-05-04 16:00:00'),
  8. (23, 650, '2018-06-05 16:00:00'),
  9. (24, 250, '2018-07-06 16:00:00'),
  10. (25, 200, '2018-08-07 16:00:00'),
  11. (26, 450, '2018-09-08 16:00:00'),
  12. (27, 750, '2018-10-09 16:00:00'),
  13. (28, 800, '2018-11-10 16:00:00'),
  14. (29, 150, '2018-12-11 16:00:00'),
  15. (30, 50, '2018-01-06 16:00:00'),
  16. (31, 50, '2018-01-16 16:00:00'),
  17. (32, 40, '2018-01-01 16:00:00'),
  18. (33, 10, '2018-01-21 16:00:00');
database sql

index.html

This is our index which contains our add data form as well as our chart.
  1. <!DOCTYPE html>
  2. <html ng-app="app">
  3. <title>Bar Chart using ChartJS, AngularJS and PHP/MySQLi</title>
  4. <meta charset="utf-8">
  5. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  6. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  7. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
  8. <style type="text/css">
  9. canvas{
  10. margin:auto;
  11. }
  12. .alert{
  13. margin-top:20px;
  14. }
  15. </style>
  16. </head>
  17. <body ng-controller="myCtrl">
  18. <div class="container">
  19. <div class="row">
  20. <div class="col-sm-3 col-md-offset-1" ng-init="fetchfruit()">
  21. <h3 class="page-header text-center">Add Purchase</h3>
  22. <div class="form-group">
  23. <label>Amount:</label>
  24. <input type="text" class="form-control" ng-model="buy.amount">
  25. </div>
  26. <div class="form-group">
  27. <label>Date:</label>
  28. <input type="date" class="form-control" ng-model="buy.date">
  29. </div>
  30. <button type="button" ng-click="purchase()" class="btn btn-primary">Buy</button>
  31. <div class="alert alert-success text-center" ng-show="success">
  32. <button type="button" class="close" aria-hidden="true" ng-click="clear()">&times;</button>
  33. {{ message }}
  34. </div>
  35. <div class="alert alert-danger text-center" ng-show="error">
  36. <button type="button" class="close" aria-hidden="true" ng-click="clear()">&times;</button>
  37. {{ message }}
  38. </div>
  39. </div>
  40. <div class="col-sm-7" ng-init="fetchsales()">
  41. <h3 class="page-header text-center">Sales Chart</h3>
  42. <canvas id="dvCanvas" height="200" width="300"></canvas>
  43. </div>
  44. </div>
  45. </div>
  46. <script src="app.js"></script>
  47. </body>
  48. </html>

app.js

This contains our angular js scripts.
  1. var app = angular.module('app', []);
  2.  
  3. app.controller('myCtrl', function ($scope, $http) {
  4.  
  5. $scope.error = false;
  6. $scope.success = false;
  7.  
  8. $scope.purchase = function(){
  9. $http.post('purchase.php', $scope.buy)
  10. .success(function(data){
  11. if(data.error){
  12. $scope.error = true;
  13. $scope.success = false;
  14. $scope.message = data.message;
  15. }
  16. else{
  17. $scope.success = true;
  18. $scope.error = false;
  19. $scope.message = data.message;
  20. $scope.fetchsales();
  21. $scope.buy = '';
  22. }
  23. });
  24. }
  25.  
  26. //this fetches the data for our table
  27. $scope.fetchsales = function(){
  28. $http.get('fetchsales.php').success(function(data){
  29.  
  30. var ctx = document.getElementById("dvCanvas").getContext('2d');
  31. var myChart = new Chart(ctx, {
  32. type: 'bar',
  33. data: {
  34. labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  35. datasets: [{
  36. label: 'Total Purchase',
  37. data: data,
  38. borderWidth: 1
  39. }]
  40. },
  41. options: {
  42. scales: {
  43. yAxes: [{
  44. ticks: {
  45. beginAtZero:true
  46. }
  47. }]
  48. }
  49. }
  50. });
  51.  
  52. });
  53. }
  54.  
  55. $scope.clear = function(){
  56. $scope.error = false;
  57. $scope.success = false;
  58. }
  59.  
  60. });

purchase.php

This is our PHP api/code in adding new data into our MySQL Database.
  1. <?php
  2.  
  3. $conn = new mysqli("localhost", "root", "", "angular");
  4.  
  5. $out = array('error' => false);
  6.  
  7. $data = json_decode(file_get_contents("php://input"));
  8.  
  9. $amount = $data->amount;
  10. $date = $data->date;
  11.  
  12. $sql = "INSERT INTO sales (amount, sale_date) VALUES ('$amount', '$date')";
  13. $query = $conn->query($sql);
  14.  
  15. if($query){
  16. $out['message'] = "Purchase added successfully";
  17. }
  18. else{
  19. $out['error'] = true;
  20. $out['message'] = "Cannot add purchase";
  21. }
  22.  
  23. echo json_encode($out);
  24.  
  25. ?>

fetchsales.php

Lastly, this is our PHP api that fetches data from our database to use in our graph.
  1. <?php
  2.  
  3. $conn = new mysqli("localhost", "root", "", "angular");
  4.  
  5. //set timezone
  6. //date_default_timezone_set('Asia/Manila');
  7.  
  8. $year = date('Y'); //2018
  9.  
  10. $out = array();
  11.  
  12. for ($month = 1; $month <= 12; $month ++){
  13. $sql="SELECT sum(amount) AS total FROM sales WHERE month(sale_date)='$month' AND year(sale_date)='$year'";
  14. $query=$conn->query($sql);
  15. $row=$query->fetch_array();
  16.  
  17. $out[]=$row['total'];
  18. }
  19.  
  20. echo json_encode($out);
  21.  
  22. ?>
That ends this tutorial. Happy Coding :)

Add new comment