Home  >  Article  >  Backend Development  >  How to implement dynamically updated horizontal statistical charts in PHP and Vue.js

How to implement dynamically updated horizontal statistical charts in PHP and Vue.js

WBOY
WBOYOriginal
2023-08-26 10:00:321353browse

How to implement dynamically updated horizontal statistical charts in PHP and Vue.js

How to implement dynamically updated horizontal statistical charts in PHP and Vue.js

Foreword:
Statistical charts are one of the important components of data visualization. In web development, PHP is used as the back-end language to handle data storage and calculation, while Vue.js is used as the front-end framework to present data and page interaction. This article will introduce how to combine PHP and Vue.js to implement dynamically updated horizontal statistical charts.

1. Preparation
Before we start, we need to install and configure the following environment:

  1. Server environment: Build a server that can run PHP code, such as Apache and Nginx wait.
  2. Database: Use MySQL or other relational database.

2. Back-end development

  1. Create database table
    First, we need to create a database table to store statistical data. For example, we create a table named "statistics ” table contains two fields: id and value.
CREATE TABLE statistics (
    id INT AUTO_INCREMENT PRIMARY KEY,
    value INT
);
  1. Backend interface
    In PHP, we can provide it to the front end by writing a backend interface. Create a file named "api.php" and write the following code:
<?php
// 设置响应头
header('Content-Type: application/json');

// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=your_database;charset=utf8', 'your_username', 'your_password');

// 查询数据
$stmt = $db->query('SELECT * FROM statistics');
$statistics = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 返回数据
echo json_encode($statistics);

The above code connects to the database through PDO, queries the statistical data, and then returns the query results to the front end in JSON format.

3. Front-end development

  1. Page structure
    To use Vue.js on the front-end to render pages and process data, we need to create an HTML file and introduce Vue.js CDN link. The specific code is as follows:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>动态更新的水平统计图表</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <canvas id="chart"></canvas>
    </div>
    <script src="app.js"></script>
</body>
</html>
  1. JavaScript code
    Create a file named "app.js" in the same directory and write the following code:
new Vue({
    el: '#app',
    data: {
        chartData: []
    },
    mounted() {
        this.getChartData();
    },
    methods: {
        getChartData() {
            fetch('api.php')
                .then(response => response.json())
                .then(data => {
                    this.chartData = data.map(item => item.value);
                    this.renderChart();
                })
                .catch(error => console.error(error));
        },
        renderChart() {
            var ctx = document.getElementById('chart').getContext('2d');
            new Chart(ctx, {
                type: 'horizontalBar',
                data: {
                    labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                    datasets: [{
                        label: '销售统计',
                        data: this.chartData,
                        backgroundColor: 'rgba(0,123,255,0.5)'
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        }
    }
});

The above code uses Vue.js to create a Vue instance, and calls the getChartData method in the mounted hook function, sends a GET request through fetch to obtain the data returned by the backend interface, then assigns the data to chartData, and calls the renderChart method to render statistics. chart.

4. Test run
Open the HTML file in the browser, and you can see the dynamically updated horizontal statistical chart. If there is new statistical data that needs to be added, the data can be added by calling the backend interface, and then the frontend will automatically obtain the latest data and update the chart.

Conclusion:
This article introduces how to implement dynamically updated horizontal statistical charts in PHP and Vue.js. Obtain statistical data from the database through the back-end interface, and use Vue.js to present the data on the front-end and implement dynamic updates of charts. This implementation method can be applied to many actual data visualization scenarios to improve user experience and data display effects.

The above is the detailed content of How to implement dynamically updated horizontal statistical charts in PHP and Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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