Line Chart using Chart.js with PHP/MySQLi

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 line chart script.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <title>Line Chart using Chart.js with PHP/MySQLi</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">Line Chart using Chart.js with PHP/MySQLi</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" required>
  22.                                 </div>
  23.                                 <div class="form-group">
  24.                                         <label>Date:</label>
  25.                                         <input type="date" class="form-control" name="sales_date" required>
  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="lineChart" style="height:250px"></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 lineChartData = {
  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.  
  104.     var lineChartCanvas          = $('#lineChart').get(0).getContext('2d')
  105.     var lineChart                = new Chart(lineChartCanvas)
  106.     var lineChartOptions = {
  107.       //Boolean - If we should show the scale at all
  108.       showScale               : true,
  109.       //Boolean - Whether grid lines are shown across the chart
  110.       scaleShowGridLines      : false,
  111.       //String - Colour of the grid lines
  112.       scaleGridLineColor      : 'rgba(0,0,0,.05)',
  113.       //Number - Width of the grid lines
  114.       scaleGridLineWidth      : 1,
  115.       //Boolean - Whether to show horizontal lines (except X axis)
  116.       scaleShowHorizontalLines: true,
  117.       //Boolean - Whether to show vertical lines (except Y axis)
  118.       scaleShowVerticalLines  : true,
  119.       //Boolean - Whether the line is curved between points
  120.       bezierCurve             : true,
  121.       //Number - Tension of the bezier curve between points
  122.       bezierCurveTension      : 0.3,
  123.       //Boolean - Whether to show a dot for each point
  124.       pointDot                : false,
  125.       //Number - Radius of each point dot in pixels
  126.       pointDotRadius          : 4,
  127.       //Number - Pixel width of point dot stroke
  128.       pointDotStrokeWidth     : 1,
  129.       //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
  130.       pointHitDetectionRadius : 20,
  131.       //Boolean - Whether to show a stroke for datasets
  132.       datasetStroke           : true,
  133.       //Number - Pixel width of dataset stroke
  134.       datasetStrokeWidth      : 2,
  135.       //Boolean - Whether to fill the dataset with a color
  136.       datasetFill             : true,
  137.       //String - A legend template
  138.       legendTemplate          : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].lineColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
  139.       //Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
  140.       maintainAspectRatio     : true,
  141.       //Boolean - whether to make the chart responsive to window resizing
  142.       responsive              : true
  143.     }
  144.    
  145.     lineChartOptions.datasetFill = false
  146.     lineChart.Line(lineChartData, lineChartOptions)
  147.  
  148.   })
  149. </script>
  150. </body>
  151. </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 line 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 :)

Add new comment