How to Create Dynamic Chart in PHP using Chart.js

Webslesson

PHP, MySql, Jquery, AngularJS, Ajax, Codeigniter, Laravel Tutorial

Friday, 4 June 2021

Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js

If you need to envision statistical data, then Graphs are one of good approach of displaying data in short picture. With the help of graphs or chart, we can easily understand the data. If you have search on internet then there different chart libraries like Google Chart, Highcharts, morris.js, chart.js and many more.

In some previous tutorial, we have already published tutorial on how to use Google Chart library and morris.js library. Now in this tutorial, we will create dynamic pie chart, doughnut and bar chart in PHP with Dynamic data using Chart.js library and Ajax. We will create live chart that means when data change chart will automatically change without refresh of web page.

Here you can find the solution fo creating chart using chart.js in a very and easy way. In this tutorial, we will create chart or graph by using retrieve data from database and load on chart. Here we will make one simple Poll application, and poll data will display via pie chart or doughnut chart or bar chart and this poll data will be fetch from Mysql database. Below you can find the screen short in which how data pie chart, doughnut chart and bar chart has been made by using chart.js library.

Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js

HTML 5 Canvas Chart

First we need to download chartjs library from Github or directly put online cdn link at the header of web page. After this in this HTML landing page, first we have to create one Poll question with three option and one submit button by using HTML Code.

After this for create Chart.js chart, here we have to create three canvas field. After create canvas field we need to send Ajax request to PHP script for fetch Poll data from database. So this ajax request will received data in JSON format and that data will parsed and supplied as the parameter into the Char.js function for create different type of graph like pie chart, doughnut chart and bar chart. Below you can find source code of index.php file.

          

How to Create Dynamic Chart in PHP using Chart.js

Sample Survey

Which is Popular Programming Language in 2021?

Pie Chart
Doughnut Chart
Bar Chart

PHP Script for Fetch Poll Data from Mysql Database

In this tutorial, we have php file with name data.php. This file will execute via AJAX request for fetch Poll data from database and after fetching data it will return data to AJAX request in JSON format. Below you can find the source of data.php file.

  $_POST["language"] ); $query = " INSERT INTO survey_table (language) VALUES (:language) "; $statement = $connect->prepare($query); $statement->execute($data); echo 'done'; > if($_POST["action"] == 'fetch') < $query = " SELECT language, COUNT(survey_id) AS Total FROM survey_table GROUP BY language "; $result = $connect->query($query); $data = array(); foreach($result as $row) < $data[] = array( 'language' =>$row["language"], 'total' => $row["Total"], 'color' => '#' . rand(100000, 999999) . '' ); > echo json_encode($data); > > ?> 

If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.

Источник

Читайте также:  Html дополнения к chrome

Creating A JavaScript Array Dynamically Via PHP

Creating A JavaScript Array Dynamically Via PHP

Update – 1 August 2013:
There are lots of suggestions in the comments that are better than my original solution. Also, with 5 years of hindsight, I’d approach it differently anyway! The way I’d do this now would be as follows:
[sourcecode language=”php”]

[/sourcecode]
So much simpler! PHP4 has almost disappeared so there’s no reason not to use json_encode. I’d recommend that you stop reading now and just go with that.

If you use PHP to create web pages, there may be times when you need to create a JavaScript array dynamically from a PHP array. This is not hard to do, but there is a trap you need to be careful of: dealing with arrays containing only a single element.

This post is for the PHP coders out there. If you don’t write code, it may not be for you.

My Original Solution

When writing the LocalCurrency WordPress plugin, I had a PHP array containing values that needed to be converted. The plugin uses AJAX techniques to do the conversions after the page has loaded, so it doesn’t slow down page load times waiting for Yahoo! Finance. The JavaScript to do this needed to access the information in the PHP array.

I decided the best way to implement this was to create a JavaScript array from the PHP array. I came up with the following code:

[sourcecode language=”php”]
// create script string to append to content. First create the value array in JavaScript.
$script = $script . «\n» . ‘ ‘. «\nvar lcValues = new Array(«;
foreach ($lc_values as $key => $value) if ($key < (count($lc_values)-1))$script = $script . $value . ‘,’;
>
else $script = $script . $value . «);\n»;
>
>
[/sourcecode]

Note: I’m not echoing the script directly. I’m appending it to a string variable, which itself will be appended to the end of the post content.

This code will create a JavaScript array and populate it with values from a PHP array called $lc_values, which has been created elsewhere. If $lc_values contains the values 25, 34 and 16 (with keys 0, 1 and 2 respectively), then the above code will create the following JavaScript:

Читайте также:  Php максимальное значение int
[sourcecode language=”js”]var lcValues = new Array(25,34,16);[/sourcecode]

Great! This is just what I want. A JavaScript array containing the 3 values will be created, and I can use it to convert the values via JavaScript.

The Problem – Arrays With A Single Element

The problem occurs when there is only one value to convert. For example, if $lc_values only contains 25, this will create:

[sourcecode language=”js”]var lcValues = new Array(25);[/sourcecode]

JavaScript will see this as an instruction to create an array with 25 elements, rather than an array with one element with a value of 25. Later, when you try to access lcValues[0], it will be undefined and will return NaN (Not a Number) when you try to use it.

You cannot use new Array() to create an array with a single numeric element.

The Solution

I got around this problem by checking the number of elements in the PHP array, using the count function. If there is more than one element, it will create the same JavaScript as the original code did. If there is only a single element (for example, 25), it will create the follow JavaScript:

[sourcecode language=”js”]
var lcValues = new Array(1);
lcValues[0]=25;
[/sourcecode]

The final code I used looks like this:

[sourcecode language=”php”]
// create script string to append to content. First create the value array in JavaScript.
$script = $script . «\n» . ‘ ‘. «\nvar lcValues = new Array(«;
if (count($lc_values)>1) foreach ($lc_values as $key => $value) if ($key < (count($lc_values)-1))$script = $script . $value . ‘,’;
>
else $script = $script . $value . «);\n»;
>
>
>
else < // can’t create an array that just has one integer element using Array()
$script = $script . «1);\nlcValues[0]=» . $lc_values[0] . «;\n»;
>
[/sourcecode]

Note: I can safely use else, because of code outside the above snippet, ensuring the PHP array will have at least one element at this point. You may need to be careful about this. If it’s possible that your PHP array may be empty, consider using elseif (count($phparrayname)==1) instead.

Final Thoughts

There are obviously different ways to do this, but this is what works for me. If it helps anyone else, great! If anyone knows a better way to do this, let me know in the comments.

16 responses on “ Creating A JavaScript Array Dynamically Via PHP ”

  1. NikolaD@freeware software May 7, 2008 at 9:22 pm And string escaping is the other nasty part since most arrays I’ve had to use cgi trough JS are actually strings. Quotes are the main problem with escaping and I find it best to replce them with character codes for JS.
  1. KnifeySpooney June 11, 2009 at 10:49 am I was about to post this and I agree. This page’s script could be turned into a one liner of . Since JSON is a subset of JavaScript, JavaScript will already know that it is an array.
  1. Stephen Cronin Post author February 24, 2010 at 2:53 pm Thanks to everyone who suggested json_encode, but I’m with Moder on this one. When I wrote this (almost 2 years ago), I was trying to avoid a dependence on PHP5. Although I use PHP5 for some of my stuff now, I still try to avoid it where possible for anything related to WordPress (which still supports PHP4).
  1. Stephen Cronin Post author February 24, 2010 at 3:00 pm Hi Ben, Didn’t see your comment there (from over a year ago)! Interesting approach! It should work – I can’t see any problem with it – but I’d still stick with an if else statement (or maybe Mike’s implode solution) because … well because the JavaScript is, well, cleaner somehow (I’m not articulating this very well). I’m not against workarounds to get something working, but only as a last resort.
  1. Stephen Cronin Post author February 24, 2010 at 2:49 pm Hi Mike, That looks like a neat solution. I’ve used implode a lot in the last year or two, but when I wrote this I wouldn’t have been that familiar with it. I’m still not sure whether I would have thought of this approach, but at least it makes sense to me. By the way, I fixed up the code in your first comment and removed the second one. I’ll have to add a way for users to do this easily.
Читайте также:  Php конвертирование xlsx в xls

Источник

Creating Dynamic Data Graph using PHP and Chart.js

If we want to visualize statistics, graphs are one of the best ways of representation. Understanding data becomes easy and obvious with the use of graphs. There are various charting libraries like Google Charts, Highcharts, Chart.js and more.

Previously, we have created example code to generate the graph using Highcharts. Let us create an example for creating graph view with the use of Chart.js library.

Creating graph view using Chart.js is simple and easy. I have created the graph output for dynamic data retrieved from the database. I have a MySQL database table tbl_marks containing student marks.

I read the mark data and supplied it to the Chart.js function to create the graph with the mark statistics.

This screenshot shows the graph output generated by Chart.js charting library with the dynamic data from the database.

chart-js-dynamic-data-graph-output

Chart HTML5 Canvas

Download Chartjs library from the GitHub and include the library files in your example. In the landing HTML page, I have a HTML5 canvas element to plot the graph output.

On loading the landing page, I send an AJAX request to the PHP to read student marks from the database. This JSON response will be parsed and supplied as the parameter to the Chart.js function to create the graph.

    BODY < width: 550PX; >#chart-container        

PHP Code to Read Student Marks from MySQL Database

The PHP file data.php is requested via AJAX to access database to read the student marks. After reading the records it returns it as JSON response. The code is,

 mysqli_close($conn); echo json_encode($data); ?> 

Источник

Оцените статью