Area 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 gonna create our MySQL Database where we get our data. 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'),
  19. (34, 250, '2017-01-04 16:00:00'),
  20. (35, 800, '2017-02-01 16:00:00'),
  21. (36, 500, '2017-03-02 16:00:00'),
  22. (37, 750, '2017-04-03 16:00:00'),
  23. (38, 550, '2017-05-04 16:00:00'),
  24. (39, 100, '2017-06-05 16:00:00'),
  25. (40, 300, '2017-07-06 16:00:00'),
  26. (41, 750, '2017-08-07 16:00:00'),
  27. (42, 700, '2017-09-08 16:00:00'),
  28. (43, 50, '2017-10-09 16:00:00'),
  29. (44, 400, '2017-11-10 16:00:00'),
  30. (45, 550, '2017-12-11 16:00:00');
database sql

index.html

This is our index which contains our add form to update our chart and the chart itself.
  1. <!DOCTYPE html>
  2. <html ng-app="app">
  3. <title>Area 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" 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-9" ng-init="fetchsales()">
  41. <h3 class="page-header text-center">Sales Chart</h3>
  42. <canvas id="dvCanvas" height="150" 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: 'line',
  33. data: {
  34. labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  35. datasets: [
  36. {
  37. label: '2017',
  38. backgroundColor: 'red',
  39. borderColor: 'red',
  40. data: data.prev,
  41. borderWidth: 1,
  42. fill: true
  43. },
  44. {
  45. label: '2018',
  46. backgroundColor: 'skyblue',
  47. borderColor: 'skyblue',
  48. data: data.year,
  49. borderWidth: 1,
  50. fill: true
  51. }
  52.  
  53. ]
  54. },
  55. options: {
  56. responsive: true,
  57. title:{
  58. display:true,
  59. text:'2017 vs 2018'
  60. },
  61. tooltips: {
  62. mode: 'index',
  63. intersect: false,
  64. },
  65. hover: {
  66. mode: 'nearest',
  67. intersect: true
  68. },
  69. scales: {
  70. xAxes: [{
  71. display: true,
  72. scaleLabel: {
  73. display: true,
  74. labelString: 'Month'
  75. }
  76. }],
  77. yAxes: [{
  78. display: true,
  79. scaleLabel: {
  80. display: true,
  81. labelString: 'Value'
  82. },
  83. ticks: {
  84. beginAtZero:true
  85. }
  86. }]
  87. }
  88. }
  89. });
  90.  
  91. });
  92. }
  93.  
  94. $scope.clear = function(){
  95. $scope.error = false;
  96. $scope.success = false;
  97. }
  98.  
  99. });

fetchsales.php

This is our PHP api that fetches data from our MySQL Database.
  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. $prev = $year - 1;
  10.  
  11. $out = array();
  12.  
  13. for ($month = 1; $month <= 12; $month ++){
  14. $sql="SELECT sum(amount) AS total FROM sales WHERE month(sale_date)='$month' AND year(sale_date)='$year'";
  15. $query=$conn->query($sql);
  16. $row=$query->fetch_array();
  17.  
  18. $out['year'][]=$row['total'];
  19. }
  20.  
  21. for ($month = 1; $month <= 12; $month ++){
  22. $sql="SELECT sum(amount) AS total FROM sales WHERE month(sale_date)='$month' AND year(sale_date)='$prev'";
  23. $pquery=$conn->query($sql);
  24. $prow=$pquery->fetch_array();
  25.  
  26. $out['prev'][]=$prow['total'];
  27. }
  28.  
  29. echo json_encode($out);
  30.  
  31. ?>

purchase.php

Lastly, this is our PHP api/code that adds data into our MySQL Table.
  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. ?>
That ends this tutorial. Happy Coding :)

Add new comment