Home > Article > Backend Development > Create a multi-chart data visualization application using PHP and Chart.js
With the continuous development of the Internet, a large amount of data is generated and stored in various network applications and systems, especially in fields such as e-commerce, social networks, finance, and manufacturing. To extract more information from this data, data visualization has become a popular method. By converting data into graphical form, users can more easily understand and analyze the data. In this article, we'll cover how to create a multi-chart data visualization application using PHP and Chart.js.
What is Chart.js?
Chart.js is an open source JavaScript library that allows the creation of interactive, dynamic and responsive charts. It supports many types of charts, such as column charts, pie charts, line charts, etc. Chart.js requires only a small amount of configuration and some HTML tags to automatically generate concise and beautiful charts. What's more, Chart.js uses the HTML5-based Canvas element to render charts, so it can run on browsers that support HTML5.
Create a multi-chart data visualization application using PHP and Chart.js
In this tutorial, we will introduce how to use PHP and Chart.js to create a simple data visualization application. We will use MySQL as the database and PHP and Chart.js for querying and visualizing the data.
Step 1: Create database table
First, we need to create a database named "sales" and create a table named "sales_data" in it. The table should contain the following fields:
Use the following SQL statement to create the table:
CREATE TABLE sales_data (
id INT NOT NULL AUTO_INCREMENT,
month DATE NOT NULL,
revenue DECIMAL (10, 2) NOT NULL,
profit DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (id)
);
We will use PHP code to add data to this table Insert some simulated sales data.
Step 2: Create a PHP script
Next, we need to create a PHP script that will connect to the MySQL database and read the sales data. This script will return a JSON-formatted data that can be used to display charts in Chart.js.
The following is the sample code of the PHP script:
ff1106be6cf6695cd8d48d58c9fb8791connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Query the MySQL database
$query = "SELECT * FROM sales_data";
$result = $conn->query($query);
//Format the query results into JSON format
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
//Close the MySQL connection
$conn->close();
?>
Please note that this script will output a JSON formatted string. This string contains all queried sales data.
Step 3: Create HTML and JavaScript files
Now, we need to create an HTML file to display the Chart.js chart, and a JavaScript file to process and draw the Chart.js chart.
The following is a sample code for an HTML file:
8b05045a5be5764f313ed5b9168a17e6
100db36a723c770d327fc0aef2ce13b1
93f0f5c25f18dab9d176bd4f6de5d30e
b2386ffb911b14667cb8f0f91ea547a7Chart.js Data Visualization Application6e916e0f7d1e588d4f442bf645aedb2f
f69d1a0eed8813f6228307491e2690d59429d6e1efad07153846e528605c447e
32d8a8489ccf6ad22016e69b0555932f2cacc6d41bbb37262a98f745aa00fbf0
9c3bca370b5104690d9ef395f2c5f8d1
6c04bd5ca3fcae76e30b72ad730ca86d
21e788de0afdbe4ffdedc853d12c32d7c2caaf3fc160dd2513ce82f021917f8b
31bf1d5b4e24f9a2df2a8454f6e05fa8c2caaf3fc160dd2513ce82f021917f8b
36cc49f0c466276486e50c850b7e4956
73a6ac4ed44ffec12cee46588e518a5e
Please note that we used the JavaScript files from the Chart.js library. We also include a custom JavaScript file (app.js) in the HTML file. This will be the JavaScript file used to query the data and draw the chart.
The following is the sample code of the JavaScript file:
//Query MySQL database
function loadSalesData(callback) {
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { callback(xhr.responseText); } } xhr.open('GET', 'sales.php'); xhr.send();
}
// Draw a line chart
function drawLineChart(id, labels, data, label) {
var ctx = document.getElementById(id).getContext('2d'); new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: label, data: data, borderColor: 'rgb(75, 192, 192)', fill: false }] }, options: { responsive: true, title: { display: true, text: '销售收入' }, tooltips: { mode: 'index', intersect: false }, hover: { mode: 'nearest', intersect: true }, scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: '月份' } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: '金额' } }] } } });
}
//Load data and draw a chart
loadSalesData(function(response) {
//解析JSON格式的数据 var data = JSON.parse(response); //获取月份和销售收入数据 var months = []; var revenues = []; for (var i = 0; i < data.length; i++) { months.push(data[i].month); revenues.push(data[i].revenue); } //绘制销售收入折线图 drawLineChart('revenue-chart', months, revenues, '销售收入'); //获取月份和利润数据 var profits = []; for (var i = 0; i < data.length; i++) { profits.push(data[i].profit); } //绘制利润折线图 drawLineChart('profit-chart', months, profits, '利润');
});
Please note that we defined two functions: loadSalesData and drawLineChart. The loadSalesData function is used to load data in JSON format from a PHP script, while the drawLineChart function is used to draw a line chart in the Canvas element.
We used an example from the Chart.js library that draws a line chart and uses sales revenue and profit data.
Step 4: Run the Application
Now, we are ready to run our application! Just upload the HTML file and JavaScript file to the web server and open the HTML file in the browser. We will get two graphs: one is the sales revenue graph and the other is the profit graph.
in conclusion
In this article, we covered how to create a multi-chart data visualization application using PHP and Chart.js. We started by creating a database table and then created a PHP script to query the data. Next, we used the Chart.js library in the HTML file and the JavaScript file to process and draw the chart. Finally, we run our application and get two beautiful line charts. Creating data visualization applications using PHP and Chart.js is very simple, and you can leverage this technology to visualize data in any web application.
The above is the detailed content of Create a multi-chart data visualization application using PHP and Chart.js. For more information, please follow other related articles on the PHP Chinese website!