Bar Chart using PHP and JS

How to create a Bar Chart using PHP and JavaScript

Bar charts fall among the basic charts, used to compare and differentiate data. Let us look at the steps involved in creating a bar chart using PHP and JavaScript with Pluscharts, a JavaScript charting library to build charts.

Step 1: Creating the MySQL table

Consider a simple table with three columns in our database. The 3 columns are namely, id, month and sales. Say there are some seven entries in here.

CREATE TABLE shop (
id INT NOT NULL,
month VARCHAR(30) NOT NULL,
sales INT NOT NULL,
 PRIMARY KEY (id),  
 UNIQUE (month)
);
INSERT INTO shop
   (id, month, sales)
VALUES
   (1, “Jan”, 50),
   (2, “Feb”, 10),
   (3, “Mar”, 20),
   (4, “Apr”, 20),
   (5, “May”, 30),
   (6, “Jun”, 10),
   (7, “Jul”, 20);

Step 2: Creating the main and database file connection

Once you have entered the data in the database, you can start with creating your project folder and the main file. But before you begin with the main code, don’t forget to create a subfolder (optional), to hold the secondary files that need to be included in the main code.

Now, let us move to create a new file, that will contain a PHP code to fetch the data from the database.

<?php

$dbservername = “localhost”;

$dbusername = “”;

$dbpassword = “”;

$dbname = “test”;

$conn = mysqli_connect($dbservername, $dbusername, $dbpassword, $dbname);

if (!$conn) {

die(“Connection failed: “. mysqli_connect_error());

}

?>

Include the file, in the main file and in order to check the connection establishment, run the code in browser, preferably Chrome. Store both sets of data, months and sales in two arrays.

<?php  

include_once ‘dbh.php’;

$sql= “SELECT*FROM shop”;

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

$shops= array();

if (mysqli_num_rows($result) >0)

{

   while ($row= mysqli_fetch_assoc($result)) {

 

   $shops[]= $row;

}

}

$a= array();

foreach ($shops as $shop) {

$a[]= $shop[‘sales’];

}

$b= array();

foreach ($shops as $shop) {

$b[]= $shop[‘month’];

}

?>

Step 3: Writing the Bar Chart example code

Create an element, where you want to render your chart, using the following code.

For example, here we create an element with id, ‘bar-chart-example’.

<div id=”bar-chart-example”></div>

Now, since Pluscharts library is built upon d3, we load d3 first and then Pluscharts, using the following scripts.

   <script src=”https://d3js.org/d3.v5.min.js”></script>

               <script src=”path-to/src/pluscharts.js”></script>

Next, assign the data from PHP variables to JS variables, using the following code.

<script type=”text/javascript”>

   var sales= <?php echo json_encode($a ); ?>;

   var months= <?php echo json_encode($b ); ?>;

The next step will be to write a JavaScript code to set up a bar chart, using the data from the database.

 pluscharts.draw({

   drawOn : ‘#bar-chart-example’,

   type: “bar”,

   dataset : {

       data: sales,

       backgroundColor: “#7d85df”, //can be array or single color

       borderColor: “#2430b6”,

       borderWidth: 2,

       label: months,

       legendLabel: “Visitors”

   },

   options : {

       barPadding: .5,

       text: {

           display: true,

           color: “#6c478c”

       },

       axes: {

           x: {

               display: true,

               min: 0,

               max: 100

           },

           y: {

               display: true

           }

       },

       legends: {

           display: true,

           width: 20,

           height: 20

       },

       size: {

           width: ‘container’, //give ‘container’ if you want width and height of initiated container

           height: ‘400’

       }

   }

});

 </script>

Let’s break this simple code further down to understand it better.

pluscharts.draw

({   })

This function is used to initiate the chart. Under this draw function, we pass the details of the chart including the data and options as argument to the draw() function.

   drawOn : ‘#bar-chart-example’,

The drawOn element is used to indicate the element where the chart is to be generated.

   type: “bar”,

The type of chart to be drawn is specified in the type element.

dataset: {

       data: sales,

       backgroundColor: “#7d85df”, //can be array or single color

       borderColor: “#2430b6”,

       borderWidth: 2,

       label: months,

       legendLabel: “Visitors”

 }

The dataset is used to insert data values, background color, border color, border width, label and legend labels. Note that here, instead of specifying the data values in data and labels, we have given the name of the array where the data is stored, which is “sales” and “labels” respectively.

options: {

       barPadding: .5,

       text: {

           display: true,

           color: “#6c478c”

       },

axes: {

           x: {

               display: true,

               min: 0,

               max: 100

           },

           y: {

               display: true

           }

       },

legends: {

           display: true,

           width: 20,

           height: 20

       },

size: {

           width: ‘container’, //give ‘container’ if you want the width and height of the initiated container

           height: ‘400’

       }

}

Options are where the whole customization of the chart is done. Here, we specify the bar padding and the colors of the bars representing the data. As the bar padding value increases, the width of the bar decreases. The color can be specified directly or a specific color code can be written. The minimum and maximum points on x and y-axis can be indicated. The axis visibility can be controlled using the display function. There are also options to set the visibility and dimensions of legends. The total size of the chart can be set here. Instead of a number, ‘container’ can be given in as a value, when there is a need to set the chart to the same width and height as its initiated container.

Sowmya

Sowmya

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright 2019 © All rights Reserved. Design by Pluscharts