Generating Visual Statistical Charts with PHP and ECharts
This article demonstrates how to use a PHP interface to retrieve data from a MySQL database and employ the ECharts library to create dynamic visual statistical charts, guiding developers through preparation, data extraction, and chart generation steps, including code examples for a bar chart.
In the context of the growing importance of data visualization, developers often need tools to quickly generate charts and reports. Using a PHP interface together with the ECharts library enables rapid creation of visual statistical charts.
Implementation Steps
1. Preparation
Ensure PHP, MySQL, and the ECharts library are installed. ECharts can be downloaded from its website or included via CDN.
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.2.1/echarts.min.js"></script>2. Retrieve Data from MySQL
Connect to a MySQL database (e.g., test_db) and fetch records from a table (e.g., user) containing name and age fields.
<?php
$dbname = 'test_db';
$host = 'localhost';
$user = 'root';
$password = '';
$conn = mysqli_connect($host, $user, $password, $dbname);
if (! $conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM user";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = array('name' => $row['name'], 'age' => (int)$row['age']);
}
}
mysqli_close($conn);
?>The code establishes a connection, queries the user table, and converts the result set into an array.
3. Generate ECharts Chart
With the retrieved data, create a bar chart using ECharts. The HTML page loads ECharts, defines a container, and sets up the chart options.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>柱状图</title>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.2.1/echarts.min.js"></script>
</head>
<body>
<!--创建容器-->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = {
title: { text: '用户年龄分布图' },
tooltip: {},
legend: { data: ['年龄'] },
xAxis: { data: ['18岁以下', '19-25岁', '26-35岁', '36-45岁', '46岁以上'] },
yAxis: {},
series: [{ name: '年龄', type: 'bar', data: [] }]
};
// 将后台获取到的数据与option中的数据对应
option.series[0].data = [
{ value: 0, name: '18岁以下' },
{ value: 0, name: '19-25岁' },
{ value: 0, name: '26-35岁' },
{ value: 0, name: '36-45岁' },
{ value: 0, name: '46岁以上' }
];
<?php
foreach ($data as $v) {
if ($v["age"] < 18) {
echo "option.series[0].data[0].value = option.series[0].data[0].value+1;";
}
if ($v["age"] >= 19 && $v["age"] <= 25) {
echo "option.series[0].data[1].value = option.series[0].data[1].value+1;";
}
if ($v["age"] >= 26 && $v["age"] <= 35) {
echo "option.series[0].data[2].value = option.series[0].data[2].value+1;";
}
if ($v["age"] >= 36 && $v["age"] <= 45) {
echo "option.series[0].data[3].value = option.series[0].data[3].value+1;";
}
if ($v["age"] > 45) {
echo "option.series[0].data[4].value = option.series[0].data[4].value+1;";
}
}
?>
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>The PHP loop iterates over the data, counts users in each age range, updates the chart configuration, and the page renders a dynamic bar chart reflecting the database contents.
Conclusion
This tutorial shows how to combine a PHP interface with the ECharts library to generate visual statistical charts. Developers can adapt the approach for other chart types, customize styles, and organize code for better maintenance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
