<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Akbar Firdiansyah</title>
    <description>The latest articles on DEV Community by Akbar Firdiansyah (@firdiansyah).</description>
    <link>https://dev.to/firdiansyah</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F292496%2Fa14b04de-d4ee-4335-812a-e69645c2e0f0.jpeg</url>
      <title>DEV Community: Akbar Firdiansyah</title>
      <link>https://dev.to/firdiansyah</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/firdiansyah"/>
    <language>en</language>
    <item>
      <title>Create Slick Database-Driven Chart With PHP, ChartJS &amp; AJAX</title>
      <dc:creator>Akbar Firdiansyah</dc:creator>
      <pubDate>Thu, 17 Dec 2020 07:42:39 +0000</pubDate>
      <link>https://dev.to/firdiansyah/create-slick-database-driven-chart-with-php-chartjs-ajax-4k02</link>
      <guid>https://dev.to/firdiansyah/create-slick-database-driven-chart-with-php-chartjs-ajax-4k02</guid>
      <description>&lt;p&gt;Charts are everywhere, turning boring facts &amp;amp; numbers into beautiful graphs. &lt;/p&gt;

&lt;p&gt;Helps us digest information easily with stunning-visualization.&lt;/p&gt;

&lt;p&gt;Nowadays, we can create charts easily with common spreadsheet programs like Libre Office or Micro$oft Office.&lt;/p&gt;

&lt;p&gt;How about web? &lt;/p&gt;

&lt;p&gt;Say you want to present information for your web visitor with interactive data visualization. &lt;/p&gt;

&lt;p&gt;Well, there are tons of cool charting libraries available to create eye-pleasing charts.&lt;/p&gt;

&lt;p&gt;In this post I want to share how to create a database-driven chart with ChartJS.&lt;/p&gt;

&lt;p&gt;ChartJS is an open source HTML5 &amp;amp; Javascript charting libraries. Official web: &lt;a href="https://chartjs.org"&gt;https://chartjs.org&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ukx1vrab--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c5hk3cbc6kcm1qs8wsgr.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ukx1vrab--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c5hk3cbc6kcm1qs8wsgr.jpeg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This will be helpful for beginner that wanted to know how to generate chart with data from database.&lt;/p&gt;

&lt;p&gt;We also will be able to update our chart data with a date picker.&lt;/p&gt;

&lt;p&gt;The output of this project will be like this:&lt;br&gt;
&lt;a href="http://demo.devkudos.com/charty/charty-demo.webm"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uW47Sp2j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/nsl2zj1t2wc4iazdwxsf.png" alt="DevKudos - Chart"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Feel free to check this live demo:&lt;br&gt;
&lt;a href="https://bit.ly/3gVUKe3"&gt;https://bit.ly/3gVUKe3&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can download complete code here:&lt;br&gt;
&lt;a href="https://bit.ly/3gXhjz2"&gt;https://bit.ly/3gXhjz2&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For this project we will use:&lt;br&gt;
Apache version 2.4.34&lt;br&gt;
PHP version 7.3.8&lt;br&gt;
MariaDB version 10.4.8&lt;br&gt;
ChartJS version 2.6.0&lt;/p&gt;

&lt;p&gt;So let's get started:&lt;br&gt;
1.Make sure you already installed Apache, PHP &amp;amp; MariaDB. If you haven't and want simplicity I suggest you to install XAMPP.&lt;/p&gt;

&lt;p&gt;2.Use any database manager tool you love, GUI like PHPMyAdmin or console based tools.&lt;/p&gt;

&lt;p&gt;3.We need to create the database, let's call it charty&lt;/p&gt;

&lt;p&gt;4.Then create one table, name it chart&lt;/p&gt;

&lt;p&gt;5.This table have two fields, duration (float) and entrydatetime (timestamp)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kQETuzTR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/okc65a0ckbmgke5hfnah.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kQETuzTR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/okc65a0ckbmgke5hfnah.png" alt="chart table structure"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;6.After you finished with database stuff, we can proceed to coding phase&lt;/p&gt;

&lt;p&gt;7.Launch your favourite IDE or Code Editor, I'm using Visual Studio Code.&lt;/p&gt;

&lt;p&gt;8.Create charty folder inside your web directory, if you installed XAMPP then it'll be ../htdocs/charty, if you install Apache separately then it will be ../www/charty. If you don't know where to locate it, please check the documentation&lt;/p&gt;

&lt;p&gt;9.This is the complete folder structure&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_yXUmpYs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/dkggy9c3mfk57yzlvs8g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_yXUmpYs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/dkggy9c3mfk57yzlvs8g.png" alt="Folder Structure"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;10.Create conn.php for database configuration, place this code inside it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
// Charty Database Configuration
$db_name = "charty";
$username = "root";
$password = "";
$servename = "localhost";
$conn = mysqli_connect($servename ,$username ,$password ,$db_name );
        mysqli_set_charset($conn ,"utf-8");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;11.Next, create index.php for our main chart generator code, place this code inside it. This file consists of several parts:&lt;/p&gt;

&lt;p&gt;The first part, PHP code that include conn.php.&lt;br&gt;
We also place our query here.&lt;br&gt;
As you realize, this is not best practices.&lt;br&gt;
I wrote like this for tutorial simplicity:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
require "conn.php";

$result = array();
$result['duration'] = '';
$result['entrydatetime'] = '';

$sql = "SELECT  SUM(duration) as duration, 
                DATE(entrydatetime) as entrydatetime 
        FROM `chart` 
        GROUP BY DATE(entrydatetime) 
        LIMIT 0, 1";
$query_result = mysqli_query($conn, $sql);

// Loop the query result
while($row = mysqli_fetch_array($query_result))
{
        $result['duration']       = $row[0];
        $result['entrydatetime']  = $row[1];
}
        mysqli_close($conn);
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second part, we need to create placeholder for our chart, perfectly served by HTML5 div tag.&lt;/p&gt;

&lt;p&gt;The datepicker element also written in pure HTML5 tag.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class='chart' style='width:100%'&amp;gt;
   &amp;lt;input type='date' onfocus='(this.type="date")' onchange='callAjax()' placeholder='entrydatetime' 
   id='start'&amp;gt;
   &amp;lt;canvas id='myChart' width='400' height='200'&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The last part, combination of Javascript and PHP code:&lt;br&gt;
We load Chart.js library from cdn.&lt;br&gt;
And we convert query result from previous section into javascript variable.&lt;br&gt;
The dt &amp;amp; lbls variables are required by chart.js lib to store chart data points.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js'&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type='text/javascript'&amp;gt;
&amp;lt;?php
echo "var dt = ['". $result['duration'] . "'];";
echo "var lbls = ['". $result['entrydatetime'] . "'];";
?&amp;gt;

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'bar',

  // The data for our dataset
  data: {
    labels: lbls,
    // Information about the dataset
    datasets: [{
      label: "Duration (s)",
      backgroundColor: 'orange',
      borderColor: 'royalblue',
      data: dt,
    }]
  },

  // Configuration options
  options: {
    layout: {
      padding: 10,
    },
    legend: {
      position: 'bottom',
    },
    title: {
      display: true,
      text: "Product Durability Test - DevKudos.com"
    },
    scales: {
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Total Duration'
        }
      }],
      xAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Entry Date'
        }
      }]
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the callAjax() function is used to do the AJAX call when datepicker changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// This function will call filter-ajax.php with selected date to retrieve data
function callAjax(){
    var start = document.getElementById("start").value
    var xhr = new XMLHttpRequest();
    var url = "http://localhost/charty/filter-ajax.php?date=" + start;
    xhr.onreadystatechange = function(){
        if(this.readyState == 4 &amp;amp;&amp;amp; this.status == 200){
            response = JSON.parse(this.responseText)
            chart.data.datasets[0].data[0] = response.duration;
            chart.data.labels[0] = response.entrydatetime;
            chart.update();
        }
    };
    xhr.open("GET", url, true);
    xhr.send();    
}
&amp;lt;/script&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The complete code for index.php&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
require "conn.php";

$result = array();
$result['duration'] = '';
$result['entrydatetime'] = '';

$sql = "SELECT  SUM(duration) as duration, 
                DATE(entrydatetime) as entrydatetime 
        FROM `chart` 
        GROUP BY DATE(entrydatetime) 
        LIMIT 0, 1";
$query_result = mysqli_query($conn, $sql);

// Loop the query result
while($row = mysqli_fetch_array($query_result))
{
        $result['duration']       = $row[0];
        $result['entrydatetime']  = $row[1];
}
        mysqli_close($conn);
?&amp;gt;

&amp;lt;div class='chart' style='width:100%'&amp;gt;
   &amp;lt;input type='date' onfocus='(this.type="date")' onchange='callAjax()' placeholder='entrydatetime' 
   id='start'&amp;gt;
   &amp;lt;canvas id='myChart' width='400' height='200'&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/div&amp;gt;

&amp;lt;script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js'&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type='text/javascript'&amp;gt;
&amp;lt;?php
echo "var dt = ['". $result['duration'] . "'];";
echo "var lbls = ['". $result['entrydatetime'] . "'];";
?&amp;gt;

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'bar',

  // The data for our dataset
  data: {
    labels: lbls,
    // Information about the dataset
    datasets: [{
      label: "Duration (s)",
      backgroundColor: 'orange',
      borderColor: 'royalblue',
      data: dt,
    }]
  },

  // Configuration options
  options: {
    layout: {
      padding: 10,
    },
    legend: {
      position: 'bottom',
    },
    title: {
      display: true,
      text: "Product Durability Test - DevKudos.com"
    },
    scales: {
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Total Duration'
        }
      }],
      xAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Entry Date'
        }
      }]
    }
  }
});

// This function will call filter-ajax.php with selected date to retrieve data
function callAjax(){
    var start = document.getElementById("start").value
    var xhr = new XMLHttpRequest();
    var url = "http://localhost/charty/filter-ajax.php?date=" + start;
    xhr.onreadystatechange = function(){
        if(this.readyState == 4 &amp;amp;&amp;amp; this.status == 200){
            response = JSON.parse(this.responseText)
            chart.data.datasets[0].data[0] = response.duration;
            chart.data.labels[0] = response.entrydatetime;
            chart.update();
        }
    };
    xhr.open("GET", url, true);
    xhr.send();    
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;12.Create filter-ajax.php, this will be called when we update datepicker. Then will return data in JSON format.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
// Ensure the response will be send as json format, otherwise error will arise
header('Content-Type: application/json');
require "conn.php";

$date = $_GET['date'];
$result = array();
$result['duration'] = '';
$result['entrydatetime'] = '';

$sql = "SELECT  SUM(duration) as duration, 
                DATE(entrydatetime) as entrydatetime 
        FROM `chart` 
        WHERE DATE(entrydatetime) = '$date'
        GROUP BY DATE(entrydatetime) LIMIT 0, 1";

$query_result = mysqli_query($conn, $sql);

while($row = mysqli_fetch_array($query_result))
{    
        $result['duration'] = $row[0];
        $result['entrydatetime'] = $row[1];
}
        echo json_encode($result);
        mysqli_close($conn);
?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;13.Finally we're ready test our chart, fire-up your favourite web browser, and visit &lt;a href="http://localhost/charty"&gt;http://localhost/charty&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That's it&lt;/p&gt;

&lt;p&gt;Just kind reminder, you can test the live result here:&lt;br&gt;
&lt;a href="https://bit.ly/3gVUKe3"&gt;https://bit.ly/3gVUKe3&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And download the source code here:&lt;br&gt;
&lt;a href="https://bit.ly/3gXhjz2"&gt;https://bit.ly/3gXhjz2&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope you enjoy this tutorial, please like &amp;amp; share if you find this helpful.&lt;/p&gt;

&lt;p&gt;If you have any questions or interesting project, feel free to poke me at &lt;a href="mailto:akbar@devkudos.com"&gt;akbar@devkudos.com&lt;/a&gt; or visit my web: &lt;a href="https://devkudos.com"&gt;https://devkudos.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ila liqo&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ajax</category>
      <category>chartjs</category>
      <category>freebies</category>
    </item>
  </channel>
</rss>
