Statistical Representation using Chart.js

Getting Started

I've used CDN for Bootstrap and jQuery in this tutorial so, you need internet connection for them to work. Chart.js used in this tutorial is included in the downloadable file of this tutorial.

Creating our Database

First, we're going to create our database. 1. Open phpMyAdmin. 2. Click databases, create a database and name it as chartjs. 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
  1. CREATE TABLE `sales` (
  2.   `salesid` INT(11) NOT NULL AUTO_INCREMENT,
  3.   `amount` DOUBLE NOT NULL,
  4.   `sales_date` DATE NOT NULL,
  5. PRIMARY KEY(`salesid`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
database sql

Inserting Data into our Database

Next, we insert sample data to our database to be used in our chart. 1. Click chartjs database that we have created earlier. 2. Click SQL and paste the following codes.
  1. INSERT INTO `sales` (`salesid`, `amount`, `sales_date`) VALUES
  2. (8, 100, '2017-01-01'),
  3. (9, 55, '2016-01-01'),
  4. (10, 200, '2017-02-02'),
  5. (11, 55, '2016-02-02'),
  6. (12, 175, '2017-03-03'),
  7. (13, 150, '2016-03-03'),
  8. (14, 150, '2017-04-04'),
  9. (15, 85, '2016-04-04'),
  10. (16, 99, '2017-04-04'),
  11. (17, 20, '2016-04-04'),
  12. (18, 180, '2017-05-05'),
  13. (19, 70, '2016-05-05'),
  14. (20, 225, '2016-06-06'),
  15. (21, 150, '2017-06-06'),
  16. (22, 120, '2017-07-07'),
  17. (23, 55, '2016-07-07'),
  18. (24, 199, '2017-08-08'),
  19. (25, 45, '2016-08-08'),
  20. (26, 130, '2017-09-09'),
  21. (27, 75, '2016-09-09'),
  22. (28, 300, '2017-10-10'),
  23. (29, 35, '2016-10-10'),
  24. (30, 250, '2017-11-11'),
  25. (31, 20, '2016-11-11'),
  26. (32, 220, '2017-12-12'),
  27. (33, 200, '2016-12-12'),
  28. (34, 45, '2016-01-05');
3. Click Go button below.

index.php

This is our index which contains our simple add form and our statistical representation of data from database. This also contains our barchart script.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <title>Statistical Representation using Chart.js</title>
  5.         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  6.         <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  7.         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  8.  
  9.         <!-- ChartJS -->
  10.         <script src="chart.js/Chart.js"></script>
  11. </head>
  12. <body>
  13. <div class="container">
  14.         <h1 class="page-header text-center">Statistical Report using Chart.js</h1>
  15.         <div class="row">
  16.                 <div class="col-md-3">
  17.                         <h3 class="page-header text-center">Add Sales</h3>
  18.                         <form method="POST" action="addsales.php">
  19.                                 <div class="form-group">
  20.                                         <label>Amount:</label>
  21.                                         <input type="text" class="form-control" name="amount">
  22.                                 </div>
  23.                                 <div class="form-group">
  24.                                         <label>Date:</label>
  25.                                         <input type="date" class="form-control" name="sales_date">
  26.                                 </div>
  27.                                 <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
  28.                         </form>
  29.                 </div>
  30.                 <div class="col-md-9">
  31.                         <div class="box box-success">
  32.             <div class="box-header with-border">
  33.                 <?php
  34.                         //set timezone
  35.                                         //date_default_timezone_set('Asia/Manila');
  36.                                         $year = date('Y');
  37.                 ?>
  38.               <h3 class="box-title">Sales Report (<?php echo $year-1; ?> vs <?php echo $year; ?>)</h3>
  39.  
  40.             </div>
  41.             <div class="box-body">
  42.               <div class="chart">
  43.                 <canvas id="barChart" style="height:230px"></canvas>
  44.               </div>
  45.             </div>
  46.             <!-- /.box-body -->
  47.           </div>
  48.                 </div>
  49.         </div>
  50. </div>
  51. <?php include('data.php'); ?>
  52. <script>
  53.   $(function () {
  54.     var barChartData = {
  55.       labels  : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  56.       datasets: [
  57.         {
  58.           label               : 'Previous Year',
  59.           fillColor           : 'rgba(210, 214, 222, 1)',
  60.           strokeColor         : 'rgba(210, 214, 222, 1)',
  61.           pointColor          : 'rgba(210, 214, 222, 1)',
  62.           pointStrokeColor    : '#c1c7d1',
  63.           pointHighlightFill  : '#fff',
  64.           pointHighlightStroke: 'rgba(220,220,220,1)',
  65.           data                : [ "<?php echo $pjan; ?>",
  66.                                   "<?php echo $pfeb; ?>",
  67.                                   "<?php echo $pmar; ?>",
  68.                                   "<?php echo $papr; ?>",
  69.                                   "<?php echo $pmay; ?>",
  70.                                   "<?php echo $pjun; ?>",
  71.                                   "<?php echo $pjul; ?>",
  72.                                   "<?php echo $paug; ?>",
  73.                                   "<?php echo $psep; ?>",
  74.                                   "<?php echo $poct; ?>",
  75.                                   "<?php echo $pnov; ?>",
  76.                                   "<?php echo $pdec; ?>"
  77.                                 ]
  78.         },
  79.         {
  80.           label               : 'This Year',
  81.           fillColor           : 'rgba(60,141,188,0.9)',
  82.           strokeColor         : 'rgba(60,141,188,0.8)',
  83.           pointColor          : '#3b8bba',
  84.           pointStrokeColor    : 'rgba(60,141,188,1)',
  85.           pointHighlightFill  : '#fff',
  86.           pointHighlightStroke: 'rgba(60,141,188,1)',
  87.           data                : [ "<?php echo $tjan; ?>",
  88.                                   "<?php echo $tfeb; ?>",
  89.                                   "<?php echo $tmar; ?>",
  90.                                   "<?php echo $tapr; ?>",
  91.                                   "<?php echo $tmay; ?>",
  92.                                   "<?php echo $tjun; ?>",
  93.                                   "<?php echo $tjul; ?>",
  94.                                   "<?php echo $taug; ?>",
  95.                                   "<?php echo $tsep; ?>",
  96.                                   "<?php echo $toct; ?>",
  97.                                   "<?php echo $tnov; ?>",
  98.                                   "<?php echo $tdec; ?>"
  99.                                 ]
  100.         }
  101.       ]
  102.     }
  103.     var barChartCanvas                   = $('#barChart').get(0).getContext('2d')
  104.     var barChart                         = new Chart(barChartCanvas)
  105.     var barChartData                     = barChartData
  106.     barChartData.datasets[1].fillColor   = '#00a65a'
  107.     barChartData.datasets[1].strokeColor = '#00a65a'
  108.     barChartData.datasets[1].pointColor  = '#00a65a'
  109.     var barChartOptions                  = {
  110.       //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
  111.       scaleBeginAtZero        : true,
  112.       //Boolean - Whether grid lines are shown across the chart
  113.       scaleShowGridLines      : true,
  114.       //String - Colour of the grid lines
  115.       scaleGridLineColor      : 'rgba(0,0,0,.05)',
  116.       //Number - Width of the grid lines
  117.       scaleGridLineWidth      : 1,
  118.       //Boolean - Whether to show horizontal lines (except X axis)
  119.       scaleShowHorizontalLines: true,
  120.       //Boolean - Whether to show vertical lines (except Y axis)
  121.       scaleShowVerticalLines  : true,
  122.       //Boolean - If there is a stroke on each bar
  123.       barShowStroke           : true,
  124.       //Number - Pixel width of the bar stroke
  125.       barStrokeWidth          : 2,
  126.       //Number - Spacing between each of the X value sets
  127.       barValueSpacing         : 5,
  128.       //Number - Spacing between data sets within X values
  129.       barDatasetSpacing       : 5,
  130.       //String - A legend template
  131.       legendTemplate          : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
  132.       //Boolean - whether to make the chart responsive
  133.       responsive              : true,
  134.       maintainAspectRatio     : true
  135.     }
  136.  
  137.     barChartOptions.datasetFill = false
  138.     barChart.Bar(barChartData, barChartOptions)
  139.  
  140.   })
  141. </script>
  142. </body>
  143. </html>

addsales.php

This is our PHP code in adding data into our database.
  1. <?php
  2.         $conn = new mysqli("localhost", "root", "", "chartjs");
  3.  
  4.         if ($conn->connect_error) {
  5.             die("Connection failed: " . $conn->connect_error);
  6.         }
  7.  
  8.         $amount=$_POST['amount'];
  9.         $sales_date=$_POST['sales_date'];
  10.  
  11.         $sql="insert into sales (amount, sales_date) values ('$amount', '$sales_date')";
  12.         $conn->query($sql);
  13.  
  14.         header('location:index.php');
  15. ?>

data.php

Lastly, this is our PHP code that contains our data that we're gonna be using in our chart.js to make statistical data in the form of bar chart.
  1. <?php
  2.         $conn = new mysqli("localhost", "root", "", "chartjs");
  3.  
  4.         if ($conn->connect_error) {
  5.             die("Connection failed: " . $conn->connect_error);
  6.         }
  7.  
  8.         //set timezone
  9.         //date_default_timezone_set('Asia/Manila');
  10.         $year = date('Y');
  11.         $total=array();
  12.         for ($month = 1; $month <= 12; $month ++){
  13.                 $sql="select *, sum(amount) as total from sales where month(sales_date)='$month' and year(sales_date)='$year'";
  14.                 $query=$conn->query($sql);
  15.                 $row=$query->fetch_array();
  16.  
  17.                 $total[]=$row['total'];
  18.         }
  19.  
  20.         $tjan = $total[0];
  21.         $tfeb = $total[1];
  22.         $tmar = $total[2];
  23.         $tapr = $total[3];
  24.         $tmay = $total[4];
  25.         $tjun = $total[5];
  26.         $tjul = $total[6];
  27.         $taug = $total[7];
  28.         $tsep = $total[8];
  29.         $toct = $total[9];
  30.         $tnov = $total[10];
  31.         $tdec = $total[11];
  32.  
  33.         $pyear = $year - 1;
  34.         $pnum=array();
  35.  
  36.         for ($pmonth = 1; $pmonth <= 12; $pmonth ++){
  37.                 $sql="select *, sum(amount) as ptotal from sales where month(sales_date)='$pmonth' and year(sales_date)='$pyear'";
  38.                 $pquery=$conn->query($sql);
  39.                 $prow=$pquery->fetch_array();
  40.  
  41.                 $ptotal[]=$prow['ptotal'];
  42.         }
  43.        
  44.         $pjan = $ptotal[0];
  45.         $pfeb = $ptotal[1];
  46.         $pmar = $ptotal[2];
  47.         $papr = $ptotal[3];
  48.         $pmay = $ptotal[4];
  49.         $pjun = $ptotal[5];
  50.         $pjul = $ptotal[6];
  51.         $paug = $ptotal[7];
  52.         $psep = $ptotal[8];
  53.         $poct = $ptotal[9];
  54.         $pnov = $ptotal[10];
  55.         $pdec = $ptotal[11];
  56. ?>
That ends this tutorial. Happy Coding :)

Comments

Nice concept nurhodelta_17, I get this error on line 16 of data.php "Fatal error: call to a member function fetch_array() on boolean" been trying to fix it to no avail

Add new comment