Doughnut 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 pie. 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
  1. CREATE TABLE `category` (
  2.   `catid` INT(11) NOT NULL AUTO_INCREMENT,
  3.   `catname` VARCHAR(30) NOT NULL,
  4. PRIMARY KEY(`catid`)
  5. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  6.  
  7. CREATE TABLE `product` (
  8.   `prodid` INT(11) NOT NULL AUTO_INCREMENT,
  9.   `catid` INT(11) NOT NULL,
  10.   `prodname` VARCHAR(30) NOT NULL,
  11. PRIMARY KEY(`prodid`)
  12. ) 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 pie database that we have created earlier. 2. Click SQL and paste the following codes.
  1. INSERT INTO `category` (`catid`, `catname`) VALUES
  2. (1, 'Samsung'),
  3. (2, 'Apple'),
  4. (3, 'Vivo'),
  5. (4, 'Sony'),
  6. (5, 'Nokia');
  7.  
  8. INSERT INTO `product` (`prodid`, `catid`, `prodname`) VALUES
  9. (2, 1, 'Galaxy Note FE '),
  10. (3, 1, 'Galaxy J7 +'),
  11. (4, 1, 'Galaxy J7 Core'),
  12. (5, 1, 'Galaxy Note 8'),
  13. (6, 1, 'Galaxy J5 Prime'),
  14. (7, 2, 'iPhone 7'),
  15. (8, 2, 'iPhone 7 +'),
  16. (9, 2, 'iPhone SE'),
  17. (10, 2, 'iPhone 6S'),
  18. (11, 3, 'Vivo Y53'),
  19. (12, 3, 'Vivo V7+'),
  20. (13, 3, 'Vivo V5'),
  21. (14, 3, 'Vivo Y55'),
  22. (15, 4, 'Sony Xperia XZ Premium'),
  23. (16, 4, 'Sony Xperia XZ1'),
  24. (17, 4, 'Sony Xperia XZ'),
  25. (18, 4, 'Sony Xperia XZs'),
  26. (19, 4, 'Sony Xperia Z5 Dual'),
  27. (20, 4, 'Sony Xperia Z5 Premium Dual'),
  28. (21, 4, 'Sony Xperia C3'),
  29. (22, 4, 'Sony Xperia C5 Ultra Dual'),
  30. (23, 5, 'Nokia 5'),
  31. (24, 5, 'Nokia 6'),
  32. (25, 5, 'Nokia Lumia 530'),
  33. (26, 5, 'Nokia Lumia 950'),
  34. (27, 4, 'Sony Xperia XA1');
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 doughnut chart script.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.         <title>Doughnut 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">Doughnut 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 Product</h3>
  18.                         <form method="POST" action="addproduct.php">
  19.                                 <div class="form-group">
  20.                                         <label>Category:</label>
  21.                                         <select class="form-control" name="category">
  22.             <?php
  23.               //connection
  24.               $conn = new mysqli("localhost", "root", "", "pie");
  25.               if ($conn->connect_error) {
  26.                 die("Connection failed: " . $conn->connect_error);
  27.               }
  28.  
  29.               $sql="select * from category";
  30.               $query=$conn->query($sql);
  31.  
  32.               while($row=$query->fetch_array()){
  33.                 ?>
  34.                 <option value="<?php echo $row['catid']; ?>"><?php echo $row['catname']; ?></option>
  35.                 <?php
  36.               }
  37.             ?>
  38.           </select>
  39.                                 </div>
  40.                                 <div class="form-group">
  41.                                         <label>Product Name:</label>
  42.                                         <input type="text" class="form-control" name="pname">
  43.                                 </div>
  44.                                 <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
  45.                         </form>
  46.                 </div>
  47.                 <div class="col-md-9">
  48.                         <div class="box box-success">
  49.             <div class="box-header with-border">
  50.                 <?php
  51.                  //set timezone
  52.                                              //date_default_timezone_set('Asia/Manila');
  53.                                              $year = date('Y');
  54.                 ?>
  55.               <h3 class="box-title">Phone Brands</h3>
  56.  
  57.             </div>
  58.             <div class="box-body">
  59.               <canvas id="pieChart" style="height:250px"></canvas>
  60.             </div>
  61.             <!-- /.box-body -->
  62.           </div>
  63.                 </div>
  64.         </div>
  65. </div>
  66. <?php include('data.php'); ?>
  67. <script>
  68.   $(function () {
  69.     var pieChartCanvas = $('#pieChart').get(0).getContext('2d')
  70.     var pieChart       = new Chart(pieChartCanvas)
  71.     var PieData        = [
  72.       {
  73.         value    : <?php echo $samsung; ?>,
  74.         color    : '#f56954',
  75.         highlight: '#f56954',
  76.         label    : 'Samsung'
  77.       },
  78.       {
  79.         value    : <?php echo $apple; ?>,
  80.         color    : '#00a65a',
  81.         highlight: '#00a65a',
  82.         label    : 'Apple'
  83.       },
  84.       {
  85.         value    : <?php echo $vivo; ?>,
  86.         color    : '#f39c12',
  87.         highlight: '#f39c12',
  88.         label    : 'Vivo'
  89.       },
  90.       {
  91.         value    : <?php echo $sony; ?>,
  92.         color    : '#00c0ef',
  93.         highlight: '#00c0ef',
  94.         label    : 'Sony'
  95.       },
  96.       {
  97.         value    : <?php echo $nokia; ?>,
  98.         color    : '#3c8dbc',
  99.         highlight: '#3c8dbc',
  100.         label    : 'Nokia'
  101.       }
  102.     ]
  103.     var pieOptions     = {
  104.       //Boolean - Whether we should show a stroke on each segment
  105.       segmentShowStroke    : true,
  106.       //String - The colour of each segment stroke
  107.       segmentStrokeColor   : '#fff',
  108.       //Number - The width of each segment stroke
  109.       segmentStrokeWidth   : 2,
  110.       //Number - The percentage of the chart that we cut out of the middle
  111.       percentageInnerCutout: 50, // This is 0 for Pie charts
  112.       //Number - Amount of animation steps
  113.       animationSteps       : 100,
  114.       //String - Animation easing effect
  115.       animationEasing      : 'easeOutBounce',
  116.       //Boolean - Whether we animate the rotation of the Doughnut
  117.       animateRotate        : true,
  118.       //Boolean - Whether we animate scaling the Doughnut from the centre
  119.       animateScale         : false,
  120.       //Boolean - whether to make the chart responsive to window resizing
  121.       responsive           : true,
  122.       // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
  123.       maintainAspectRatio  : true,
  124.       //String - A legend template
  125.       legendTemplate       : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
  126.     }
  127.     //Create pie or douhnut chart
  128.     // You can switch between pie and douhnut using the method below.
  129.     pieChart.Doughnut(PieData, pieOptions)
  130.  
  131.   })
  132. </script>
  133. </body>
  134. </html>

addproduct.php

This is our PHP code in adding data into our database.
  1. <?php
  2.         $conn = new mysqli("localhost", "root", "", "pie");
  3.  
  4.         if ($conn->connect_error) {
  5.             die("Connection failed: " . $conn->connect_error);
  6.         }
  7.  
  8.         $category=$_POST['category'];
  9.         $pname=$_POST['pname'];
  10.  
  11.         $sql="insert into product (catid, prodname) values ('$category', '$pname')";
  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 doughnut chart.
  1. <?php
  2.         $conn = new mysqli("localhost", "root", "", "pie");
  3.  
  4.         if ($conn->connect_error) {
  5.             die("Connection failed: " . $conn->connect_error);
  6.         }
  7.  
  8.         //$cat = array();
  9.  
  10.         //for Samsung
  11.         $sql="select * from product left join category on category.catid=product.catid where product.catid='1'";
  12.         $query=$conn->query($sql);
  13.         $samsung = $query->num_rows;
  14.  
  15.         //for Apple
  16.         $sql="select * from product left join category on category.catid=product.catid where product.catid='2'";
  17.         $aquery=$conn->query($sql);
  18.         $apple = $aquery->num_rows;
  19.  
  20.         //for Vivo
  21.         $sql="select * from product left join category on category.catid=product.catid where product.catid='3'";
  22.         $vquery=$conn->query($sql);
  23.         $vivo = $vquery->num_rows;
  24.  
  25.         //for Sony
  26.         $sql="select * from product left join category on category.catid=product.catid where product.catid='4'";
  27.         $squery=$conn->query($sql);
  28.         $sony = $squery->num_rows;
  29.  
  30.         //for Nokia
  31.         $sql="select * from product left join category on category.catid=product.catid where product.catid='5'";
  32.         $nquery=$conn->query($sql);
  33.         $nokia = $nquery->num_rows;
  34.  
  35. ?>
  36. <php>
  37.  
  38. That ends this tutorial. Happy Coding :)

Add new comment