How can Echarts retrieve data from the database?

To retrieve data from a database and use it in ECharts, you can connect to the database using backend languages like PHP, Python, Node.js, etc., convert the query results into JSON format, and then pass the data to the frontend page through AJAX requests for display in ECharts.

Here is a simple example code, assuming you are using PHP as the backend language.

  1. PHP file (getData.php):
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);

// 查询数据库获取数据
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

$data = array();
while($row = $result->fetch_assoc()) {
    $data[] = array(
        'name' => $row['name'],
        'value' => $row['value']
    );
}

// 输出数据为 JSON 格式
echo json_encode($data);

// 关闭数据库连接
$conn->close();
?>
  1. Use AJAX requests in the front-end to retrieve data and display it in ECharts.
<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.2.2/echarts.min.js"></script>
</head>
<body>
    <div id="chart" style="width: 600px; height: 400px;"></div>
    <script>
        var chart = echarts.init(document.getElementById('chart'));

        // 使用 AJAX 请求获取数据
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'getData.php', true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var data = JSON.parse(xhr.responseText);

                // 在 ECharts 中使用数据创建图表
                chart.setOption({
                    xAxis: {
                        type: 'category',
                        data: data.map(function(item) {
                            return item.name;
                        })
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [{
                        data: data.map(function(item) {
                            return item.value;
                        }),
                        type: 'bar'
                    }]
                });
            }
        };
        xhr.send();
    </script>
</body>
</html>

Please adjust the database connection and query logic in the code, as well as the configuration of the ECharts chart, based on your actual situation. This is a simple example that can be adapted for more complex data processing and chart display as needed.

bannerAds