Home Backend Development PHP Tutorial How to use ECharts and php interface to generate statistical charts

How to use ECharts and php interface to generate statistical charts

Dec 18, 2023 pm 01:47 PM
php echarts summary graph

How to use ECharts and php interface to generate statistical charts

How to use ECharts and PHP interface to generate statistical charts

Introduction:
In modern web application development, data visualization is a very important link, it can Help us visually display and analyze data. ECharts is a powerful open source JavaScript chart library. It provides a variety of chart types and rich interactive functions, and can easily generate various statistical charts. This article will introduce how to use ECharts and PHP interfaces to generate statistical charts, and give specific code examples.

1. Overview
ECharts is a customizable chart library open sourced by Baidu. It supports a variety of chart types, including line charts, bar charts, pie charts, etc., and provides rich interactions and animation effects. PHP is a commonly used server-side language for processing data and interacting with databases. By combining ECharts and PHP, we can easily obtain data from the database and use it to generate statistical charts.

2. Environment preparation
Before we start, we need to install and configure the following software and libraries:

  1. PHP environment: To use PHP scripts, we need to install PHP and Configure the web server (such as Apache).
  2. ECharts library: Download the latest ECharts library from the ECharts official website and introduce it into the HTML page.

3. Obtain data
Before generating statistical charts, we first need to obtain data from the database. The following is a simple PHP script to connect to the database and obtain data:

// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$conn) {

die('数据库连接失败: ' . mysqli_connect_error());

}

// Query data
$sql = "SELECT * FROM statistics";
$result = mysqli_query($conn, $sql);

// Processing results
$data = array();
while ($row = mysqli_fetch_assoc($result)) {

$data[] = array(
    'name' => $row['name'],
    'value' => $row['value']
);

}

//Output data
echo json_encode($data);

//Close database connection
mysqli_close($conn);
?>

4. Generate statistical charts
Next, we generate statistical charts through ECharts and PHP interfaces. The following is a simple HTML page for drawing a bar chart:



<meta charset="utf-8">
<title>ECharts统计图表</title>
<script src="echarts.min.js"></script>


<div id="chart" style="width: 800px; height: 400px;"></div>
<script>
    // 使用ajax获取数据
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'data.php', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var data = JSON.parse(xhr.responseText);
            renderChart(data);
        }
    };
    xhr.send();

    // 渲染图表
    function renderChart(data) {
        var chart = echarts.init(document.getElementById('chart'));

        var option = {
            title: {
                text: '数据统计'
            },
            xAxis: {
                type: 'category',
                data: data.map(function(item) {
                    return item.name;
                })
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                type: 'bar',
                data: data.map(function(item) {
                    return item.value;
                })
            }]
        };

        chart.setOption(option);
    }
</script>

The above is the detailed content of How to use ECharts and php interface to generate statistical charts. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
How to work with arrays in php How to work with arrays in php Aug 20, 2025 pm 07:01 PM

PHParrayshandledatacollectionsefficientlyusingindexedorassociativestructures;theyarecreatedwitharray()or[],accessedviakeys,modifiedbyassignment,iteratedwithforeach,andmanipulatedusingfunctionslikecount(),in_array(),array_key_exists(),array_push(),arr

Compare and contrast PHP Traits, Abstract Classes, and Interfaces with practical use cases. Compare and contrast PHP Traits, Abstract Classes, and Interfaces with practical use cases. Aug 11, 2025 pm 11:17 PM

Useinterfacestodefinecontractsforunrelatedclasses,ensuringtheyimplementspecificmethods;2.Useabstractclassestosharecommonlogicamongrelatedclasseswhileenforcinginheritance;3.Usetraitstoreuseutilitycodeacrossunrelatedclasseswithoutinheritance,promotingD

Fix: Ethernet 'Unidentified Network' Fix: Ethernet 'Unidentified Network' Aug 12, 2025 pm 01:53 PM

Restartyourrouterandcomputertoresolvetemporaryglitches.2.RuntheNetworkTroubleshooterviathesystemtraytoautomaticallyfixcommonissues.3.RenewtheIPaddressusingCommandPromptasadministratorbyrunningipconfig/release,ipconfig/renew,netshwinsockreset,andnetsh

How to use the $_COOKIE variable in php How to use the $_COOKIE variable in php Aug 20, 2025 pm 07:00 PM

$_COOKIEisaPHPsuperglobalforaccessingcookiessentbythebrowser;cookiesaresetusingsetcookie()beforeoutput,readvia$_COOKIE['name'],updatedbyresendingwithnewvalues,anddeletedbysettinganexpiredtimestamp,withsecuritybestpracticesincludinghttponly,secureflag

Describe the Observer design pattern and its implementation in PHP. Describe the Observer design pattern and its implementation in PHP. Aug 15, 2025 pm 01:54 PM

TheObserverdesignpatternenablesautomaticnotificationofdependentobjectswhenasubject'sstatechanges.1)Itdefinesaone-to-manydependencybetweenobjects;2)Thesubjectmaintainsalistofobserversandnotifiesthemviaacommoninterface;3)Observersimplementanupdatemetho

phpMyAdmin security best practices phpMyAdmin security best practices Aug 17, 2025 am 01:56 AM

To effectively protect phpMyAdmin, multiple layers of security measures must be taken. 1. Restrict access through IP, only trusted IP connections are allowed; 2. Modify the default URL path to a name that is not easy to guess; 3. Use strong passwords and create a dedicated MySQL user with minimized permissions, and it is recommended to enable two-factor authentication; 4. Keep the phpMyAdmin version up to fix known vulnerabilities; 5. Strengthen the web server and PHP configuration, disable dangerous functions and restrict file execution; 6. Force HTTPS to encrypt communication to prevent credential leakage; 7. Disable phpMyAdmin when not in use or increase HTTP basic authentication; 8. Regularly monitor logs and configure fail2ban to defend against brute force cracking; 9. Delete setup and

Using XSLT Parameters to Create Dynamic Transformations Using XSLT Parameters to Create Dynamic Transformations Aug 17, 2025 am 09:16 AM

XSLT parameters are a key mechanism for dynamic conversion through external passing values. 1. Use declared parameters and set default values; 2. Pass the actual value from application code (such as C#) through interfaces such as XsltArgumentList; 3. Control conditional processing, localization, data filtering or output format through $paramName reference parameters in the template; 4. Best practices include using meaningful names, providing default values, grouping related parameters, and performing value verification. The rational use of parameters can make XSLT style sheets highly reusable and maintainable, and the same style sheets can produce diversified output results based on different inputs.

You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

See all articles