Generating Visual Statistical Charts with PHP and ECharts

This tutorial explains how to retrieve data from a MySQL database using PHP, process it, and render interactive bar charts with the ECharts library, providing step‑by‑step instructions, sample code, and best practices for creating data visualizations in web applications.

php Courses
php Courses
php Courses
Generating Visual Statistical Charts with PHP and ECharts

In the era of increasing importance of data visualization, developers often need to quickly generate charts and reports to help decision makers interpret data. This article demonstrates how to use a PHP interface together with the ECharts library to create visual statistical charts.

Implementation Steps:

1. Preparation

Ensure PHP, MySQL, and the ECharts library are installed. ECharts can be downloaded from http://echarts.baidu.com/index.html 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 user table 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 script establishes a database connection, queries all rows from the user table, and stores the results in an array.

3. Generate ECharts Chart

Using the retrieved data, a bar chart is created. The example below shows an HTML page that initializes ECharts, defines a chart option, and fills the series data based on age ranges.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Bar Chart</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.2.1/echarts.min.js"></script>
</head>
<body>
    <!-- Chart container -->
    <div id="main" style="width: 600px;height:400px;"></div>
    <script type="text/javascript">
        var myChart = echarts.init(document.getElementById('main'));
        var option = {
            title: { text: 'User Age Distribution' },
            tooltip: {},
            legend: { data: ['Age'] },
            xAxis: { data: ['Under 18','19-25','26-35','36-45','46+'] },
            yAxis: {},
            series: [{ name: 'Age', type: 'bar', data: [] }]
        };
        option.series[0].data = [
            { value: 0, name: 'Under 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 fetched data, increments the appropriate age‑group counters, and injects JavaScript statements that update the ECharts option. When the page loads, ECharts renders a bar chart reflecting the distribution of ages in the database.

Conclusion

We have successfully demonstrated how to combine a PHP backend with the ECharts library to produce visual statistical charts. In real projects you can choose different chart types, customize styles, and separate data and configuration files for better maintainability.

This guide should help you quickly create various visualizations using PHP and ECharts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Chart Generation
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.