Creating Dynamic Data Graph using PHP and Chart.js

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A PHP wrapper for nnnick/Chart.js

HugoHeneault/Chart.js-PHP

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Html css кнопка иконка

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

[NOT MAINTAINED] Chart.js-PHP

Adam is now maintaining an updated version on https://github.com/Ejdamm/Chart.js-PHP, please use this one!

A PHP wrapper for nnnick/Chart.js

When using a lot of charts in a project, we need to write a lot of code.

This small PHP wrapper use data-attributes to load chart with Chart.js with less code.

Include Chart.js and chart.js-php.js before the end of your body (change src according to your project)

html> body>  script src pl-s">js/Chart.js">script> script src pl-s">js/chart.js-php.js">script> body> html>

Load ChartJS-PHP classes or use an autoloader

require 'class/ChartJS.php'; require 'class/ChartJS_Line.php';

Then, create your charts using PHP.

$Line = new ChartJS_Line('example', 500, 500); $Line->addLine(array(1, 2, 3, 4)); $Line->addLabels(array('A label', 'Another', 'Another one', 'The last one')); // Echo your line echo $Line; ?>

Finally, load these charts with a small piece of javascript when your document is ready

// Pure JS document.ready (function()  loadChartJsPhp(); >)();

Have a look at the wiki (soon)

 require 'class/ChartJS.php'; require 'class/ChartJS_Line.php'; $Line = new ChartJS_Line('example', 500, 500); $Line->addLine(array(1, 2, 3, 4)); $Line->addLabels(array('A label', 'Another', 'Another one', 'The last one')); ?>> html> head> title>Chart.js-PHPtitle> head> body>  echo $Line; ?> script src pl-s">Chart.js">script> script src pl-s">chart.js-php.js">script> script> (function()  loadChartJsPhp(); >)(); script> body> html>

Do not hesitate to edit or improve my code with bugfix and new functionnalities !

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A PHP wrapper for chartjs/Chart.js

License

Ejdamm/chart.js-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A PHP wrapper for chartjs/Chart.js This project is an expansion of HugoHeneault’s repository

Include js/Chart.min.js and js/driver.js before the end of your body (change src according to your project). If you want to use CDN instead see [here](. For CDN see here https://cdnjs.com/libraries/Chart.js)

html> body>  script src pl-s">js/Chart.min.js">script> script src pl-s">js/driver.js">script> body> html>

Install ChartJS-PHP via composer

< "repositories": [ < "type": "git", "url": "https://github.com/Ejdamm/Chart.js-PHP" >], "require": < "ejdamm/chart.js-php": "dev-master" > >

Then, create your charts using PHP.

$data = [ 'labels' => ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], 'datasets' => [[ 'data' =>[8, 7, 8, 9, 6], 'backgroundColor' => '#f2b21a', 'borderColor' => '#e5801d', 'label' => 'Legend' ]] ]; $options = []; $attributes = ['id' => 'example', 'width' => 500, 'height' => 500]; $Line = new ChartJs\ChartJS('line', $data, $options, $attributes); // Echo your line echo $Line; ?>

Finally, load these charts with a small piece of javascript when your document is ready

// Pure JS document.ready (function()  loadChartJsPhp(); >)();
 require 'vendor/autoload.php'; use ChartJs\ChartJS; $data = [ 'labels' => ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], 'datasets' => [[ 'data' =>[8, 7, 8, 9, 6], 'backgroundColor' => '#f2b21a', 'borderColor' => '#e5801d', 'label' => 'Legend' ]] ]; $options = ['responsive' => false]; $attributes = ['id' => 'example', 'width' => 500, 'height' => 500]; $Line = new ChartJS('line', $data, $options, $attributes); ?>> html> head> title>Chart.js-PHPtitle> head> body>  echo $Line; ?> script src pl-s">vendor/Ejdamm/Chart.js-PHP/js/Chart.min.js">script> script src pl-s">vendor/Ejdamm/Chart.js-PHP/js/driver.js">script> script> (function()  loadChartJsPhp(); >)(); script> body> html>

Full documentation is available at Chart.js website. There you can find what type of charts and associated properties are available.

If you are going to use time axis you need either to include Moment.js or Chart.bundle.js instead of Chart.js to your project. Chart.bundle.js consists of both Chart.js and Moment.js (which is needed for time axis).

Do not hesitate to edit or improve my code with bugfix and new functionalities!

Источник

Using Chart JS with PHP and MySQL

Chart JS is a very comprehensive framework for creating and customizing many charts and graphs. The ease of use and ability to configure the charts makes Chart JS a good choice for HTML5 charts.

Getting Chart JS to work with PHP and MySQL isn’t hard nor extensive. Here is how it is done:

Making a bar chart

Assume I have a database table that has an int column (value) and a datetime column (date_time). I am going to create a bar chart to show these values along with the date in a bar chart.

prepare("SELECT `value`, `date_time` FROM `data` ORDER BY `date_time`;"); $select->execute(); $data = array(); while ($row = $select->fetch(PDO::FETCH_ASSOC)) < $data[] = $row; >print json_encode($data);

This will jsut print out the data as an array. This is what Chart JS uses to plot the points.

$(document).ready(function () < $.ajax(< url: "create_data.php", type: "GET", success: function (data) < var date_time = []; var value = []; for (var i in data) < date_time.push("" + data[i].date_time); value.push(data[i].value); >var chartdata = < labels: date_time, datasets: [ < label: "value", fill: false, lineTension: 0.3, backgroundColor: chartColors.green, borderColor: chartColors.green, pointHoverBackgroundColor: chartColors.green, pointHoverBorderColor: chartColors.green, hoverBackgroundColor: chartColors.gold, data: value, yAxisID: "y-axis-1" >] >; var ctx = $("#value-data"); var LineGraph = new Chart(ctx, < type: 'bar', data: chartdata, options: < title: < display: true, text: '', maintainAspectRatio: false, fontColor: chartColors.green >, responsive: true, scales: < xAxes: [< display: true, scaleLabel: < display: true, labelString: '' >>], yAxes: [ < type: "linear", display: true, position: "left", id: "y-axis-1", scaleLabel: < display: false, labelString: 'value' >>] > > >); >, error: function (data) < >>); >); window.chartColors = < red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', gold: 'rgb(248,193,28)', grey: 'rgb(201, 203, 207)' >;

Looks confusing right? Most of the above is just options and configuration as per the docs. You can see that i am after the value and date_time columns, these obviously are also the points on the axis.

The colors are defined at the end, this was to save repeating a hex code and to create readability. Here is an example

Chart JS PHP MySQL exampleMaking resource friendly

One issue with this current code is its lack of sustainability in resource usage. Every time someone goes to your chart page the database gets queried. You may not be getting 100 views per minute to your graph page but that doesn’t mean you can write code that has poor practice.

This becomes even more dependent when you start filtering, fetching more data per row (multiple bars) and formating the returned date time.

Avoiding this is simple, instead of create_data.php returning the array you get it to create a JSON file with the data in it.

prepare("SELECT `value`, `date_time` FROM `data` ORDER BY `date_time`;"); $select->execute(); $data = array(); while ($row = $select->fetch(PDO::FETCH_ASSOC)) < $data[] = $row; >$fp = fopen('value_data.json', 'w'); fwrite($fp, json_encode($data)); fclose($fp);

Just point a cron job to call create_data.php thus updating the JSON file (value_chart.json).

Now when your chart page is viewed instead of the database being queried every single time, the JSON file gets loaded. Just remember to cron create_data.php every 2 or 5 minutes etc.

Источник

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); ?> 

Источник

Chart.js, MySQL & PHP for Beginners

If you are new to webdev and want to learn how to incorporate charts and graphs in your webpages this article is for you. The Northwind database is used in this article. You can find the sql file in this repository. Setup the config folder with the following files and code in it. The code below will allow you to connect to MySQL. config/config.php

Image description

After setting up the config directory you can now work on the webpage where you want to display your chart. Chart No. 1: Pie Chart Add the Chartjs script inside head tag.

 0) < // array for data $Count_Orders = array(); // array for labels (x-axis) $label_piechart = array(); while ($row = mysqli_fetch_array($result01))< $Count_Orders[] = $row['Count_Orders']; $label_piechart[] = $row['CompanyName']; >// Free result mysqli_free_result($result01); // Close the connection mysqli_close($conn); >else < echo "No records matching your query were found."; >?> 

Create a script tag below the PHP code. There will be three blocks inside the script, setup, config, and render block.

  

Image description

Chart No. 2 Line Chart Prepare canvas tag.

 // Free result mysqli_free_result($result_top3); $Top1_Count = array_fill(0,12,0); $Top2_Count = array_fill(0,12,0); $Top3_Count = array_fill(0,12,0); for ($counter=0; $counter 0) < while ($row = mysqli_fetch_array($result02))< if ($counter==0)< $Top1_Count[$row['Month_1997']] = $row['num_order']; >elseif ($counter==1) < $Top2_Count[$row['Month_1997']] = $row['num_order']; >else < $Top3_Count[$row['Month_1997']] = $row['num_order']; >> > > ?> 
  

Image description

Chart No. 3 Bar Graph (with 2 datasets) Prepare canvas for the chart.

PHP code that fetches the number of orders per month of Products under Meat/Poultry and Seafood categories.

 0)< $Sales_Meat = array(); $Sales_Seafood = array(); while ($row = mysqli_fetch_array($result03))< if($row['CategoryName']=='Seafood')< $Sales_Seafood[] = $row['sales']; >else < $Sales_Meat[] = $row['sales']; >> // print_r($Sales_Seafood); // print_r($Sales_Meat); // Free result mysqli_free_result($result03); // Close the connection mysqli_close($conn); >else < echo "No records matching your query were found."; >?> 
  

Image description

Chart No. 4 Bar Chart (one dataset) Prepare canvas.

 0) < $order_count = array(); $label_barchart = array(); while ($row = mysqli_fetch_array($result04))< $order_count[] = $row['order_count']; $label_barchart[] = $row['ProductName']; >// print_r($label_barchart); // Free result mysqli_free_result($result04); // Close the connection mysqli_close($conn); >else < echo "No records matching your query were found."; >?> 
  

Источник

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