Pie/Doughnut 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 `fruits` (
  2.   `fruitid` int(11) NOT NULL AUTO_INCREMENT,
  3.   `fruitname` varchar(30) NOT NULL,
  4. PRIMARY KEY(`fruitid`)
  5.  
  6. CREATE TABLE `sales` (
  7.   `saleid` int(11) NOT NULL AUTO_INCREMENT,
  8.   `fruitid` int(11) NOT NULL,
  9.   `amount` double NOT NULL,
  10. PRIMARY KEY(`saleid`)
  1. INSERT INTO `fruits` (`fruitid`, `fruitname`) VALUES
  2. (1, 'Apple'),
  3. (2, 'Orange'),
  4. (3, 'Strawberry'),
  5. (4, 'Mango');
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>Pie/Doughnut 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>Select Fruit:</label>
  24.                                 <select ng-model="buy.fruitid" class="form-control">
  25.                                         <option ng-repeat="fruit in fruits" value="{{fruit.fruitid}}">{{fruit.fruitname}}</option>
  26.                                 </select>
  27.                         </div>
  28.                         <div class="form-group">
  29.                                 <label>Amount:</label>
  30.                                 <input type="text" class="form-control" ng-model="buy.amount">
  31.                         </div>
  32.                         <button type="button" ng-click="purchase()" class="btn btn-primary">Buy</button>
  33.                         <div class="alert alert-success text-center" ng-show="success">
  34.                                 <button type="button" class="close" aria-hidden="true" ng-click="clear()">&times;</button>
  35.                                 {{ message }}
  36.                         </div>
  37.                         <div class="alert alert-danger text-center" ng-show="error">
  38.                                 <button type="button" class="close" aria-hidden="true" ng-click="clear()">&times;</button>
  39.                                 {{ message }}
  40.                         </div>
  41.                 </div>
  42.                 <div class="col-sm-7" ng-init="fetchsales()">
  43.                         <h3 class="page-header text-center">Sales Chart</h3>
  44.                         <canvas id="dvCanvas" height="400" width="400"></canvas>
  45.             </div>
  46.         </div>
  47. </div>
  48. <script src="app.js"></script>
  49. </body>
  50. </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.fetchfruit = function(){
  9.         $http.get('fetchfruit.php').success(function(data){
  10.             $scope.fruits = data;
  11.         });
  12.     }
  13.  
  14.     $scope.purchase = function(){
  15.         $http.post('purchase.php', $scope.buy)
  16.         .success(function(data){
  17.             if(data.error){
  18.                 $scope.error = true;
  19.                 $scope.success = false;
  20.                 $scope.message = data.message;
  21.             }
  22.             else{
  23.                 $scope.success = true;
  24.                 $scope.error = false;
  25.                 $scope.message = data.message;
  26.                 $scope.fetchsales();
  27.                 $scope.buy = '';
  28.             }
  29.         });
  30.     }
  31.  
  32.     //this fetches the data for our table
  33.     $scope.fetchsales = function(){
  34.         $http.get('fetchsales.php').success(function(data){
  35.             var ctx = document.getElementById("dvCanvas").getContext('2d');
  36.             var myChart = new Chart(ctx, {
  37.                 type: 'pie', // change the value of pie to doughtnut for doughnut chart
  38.                 data: {
  39.                     datasets: [{
  40.                         data: data.total,
  41.                         backgroundColor: ['blue', 'green', 'red', 'yellow']
  42.                     }],
  43.                     labels: data.fruitname
  44.                 },
  45.                 options: {
  46.                     responsive: false
  47.                 }
  48.             });
  49.  
  50.         });
  51.     }
  52.  
  53.     $scope.clear = function(){
  54.         $scope.error = false;
  55.         $scope.success = false;
  56.     }
  57.  
  58. });

fetchfruit.php

This is our PHP api that fetches data for our add form.
  1. <?php
  2.  
  3.         $conn = new mysqli("localhost", "root", "", "angular");
  4.  
  5.         $out = array();
  6.  
  7.         $sql = "SELECT * FROM fruits";
  8.         $query = $conn->query($sql);
  9.  
  10.         while($row=$query->fetch_array()){
  11.             $out[] = $row;
  12.         }
  13.  
  14.         echo json_encode($out);
  15.  
  16. ?>

purchase.php

This is our PHP api/code that adds data into our 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.         $fruitid = $data->fruitid;
  10.         $amount = $data->amount;
  11.  
  12.         $sql = "INSERT INTO sales (fruitid, amount) VALUES ('$fruitid', '$amount')";
  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 for our chart.
  1. <?php
  2.  
  3.         $conn = new mysqli("localhost", "root", "", "angular");
  4.  
  5.         $out = array();
  6.  
  7.         $sql = "SELECT *, sum(amount) AS total FROM sales LEFT JOIN fruits ON fruits.fruitid=sales.fruitid GROUP BY sales.fruitid";
  8.         $query = $conn->query($sql);
  9.  
  10.         while($row=$query->fetch_array()){
  11.             $out['total'][] = $row['total'];
  12.             $out['fruitname'][] = $row['fruitname'];
  13.         }
  14.  
  15.         echo json_encode($out);
  16.  
  17. ?>
That ends this tutorial. Happy Coding :)

Add new comment