Create a multi-chart data visualization application using PHP and Chart.js

WBOY
Release: 2023-05-11 11:36:02
Original
1558 people have browsed it

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:

  • id: self-increment ID
  • month: sales month
  • revenue: sales revenue
  • profit: profit

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:

//Connect to the MySQL database
$username = "root";
$ password = "";
$database = "sales";
$server = "localhost";

$conn = new mysqli($server, $username, $password, $database);

//Check whether the connection is successful
if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);
Copy after login

}

//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;
Copy after login

}

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:




Chart.js Data Visualization Application






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();
Copy after login

}

// 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: '金额'
                }
            }]
        }
    }
});
Copy after login

}

//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, '利润');
Copy after login

});

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!