Draw charts with PHP and Chart.js

Tram Ho

Introduce

Nowadays, the management websites have become more and more diversified, so the statistical management and reporting is quite common. To make data statistics more intuitive, the chart is one of the great support tools. What is a chart? What are the advantages of graphical representation of data?

A diagram is a graphical representation of data, often used to compare and recognize differences and to know the specific ratio of each component to the whole.

The advantage of representing data with graphs is that it makes it easy to compare data to make a forecast of data trends.

There are many different types of charts and drawing these charts on the website is very easy because there are so many supporting libraries such as ChartJS , Google Charts , Highcharts JS

What is ChartJS ? Chart.js is an open-source library that supports bar, line, area, pie (radar), radar, polar chart types … ChartJS is responsive by default, making it work on multiple platforms. than. ChartJS is undoubtedly one of the most impressive open source libraries of charts lately.

In this article, I will use ChartJS in combination with PHP, MySQL to display graphs in the most simple way, from which you can customize yourself to make your chart more suitable and beautiful.

Create the database

First we need to create a database to contain the information to create a chart:

Directory structure

There will be a root directory containing files such as data.php to retrieve data from the server, database.php to connect to the database, file index.php to represent data in the form of charts, and js directory yet. Libraries like jquery and Chart.js.

1. database.php

Next, you need a file to connect to the MySQL database:

2. data.php

The data.php file will query the table and export the extracted data from the MySQL database and encode as json.

To check the results, you can access the link to the file for example: http: //localhost/graph/data.php

3. index.php

In it we use the post function on the previously processed data.php file to get the data returned as JSON. After receiving the returned data, it will be assigned to each label and data for each label.

Once the data has been assigned, we can proceed with custom colors for the chart by setting bordercolor and backgroundcolor as you like.

$("#graph"); Is the ID of the card where you want to display your chart.

After completing the steps above, you have to create a Chart with the type of chart you want. Chart.js supports many types of charts such as:

  • line
  • bar
  • radar

Or you can draw a bar chart as follows

Conclude

The article above is a simple example of ChartJS hope it will help you in the first step of understanding the chart on the website.

To learn more, you can refer to Chart.js or some other documents to customize the chart for more beautiful.

Share the news now

Source : Viblo