With the growing demand for data analysis and visualization, charts are increasingly used in web applications. Combining PHP with Vue.js enables real-time data display, keeping charts updated with the latest information. This article explains the full implementation process.
Before starting, ensure you have PHP and Vue.js installed and set up. You also need a PHP backend server providing data APIs and a frontend Vue.js application.
On the PHP backend, we need to create a data API that provides the data required by the chart. You can use PDO or mysqli to access the database and return the query results as JSON to the frontend.
<?php // Connect to the database $pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); // Query data $stmt = $pdo->prepare("SELECT * FROM statistics"); $stmt->execute(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); // Return JSON data header('Content-Type: application/json'); echo json_encode($data); ?>
The code above connects to a MySQL database named 'test', queries all records from the 'statistics' table, and returns the data to the frontend in JSON format.
On the frontend, Vue.js is used to display charts and update data in real time. First, include Vue.js and the ECharts library in your HTML.
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/echarts@5.2.2/dist/echarts.min.js"></script>
Then define your Vue instance with data and methods.
<div id="app"> <div ref="chart" style="width: 600px; height: 400px;"></div> </div> <script> new Vue({ el: '#app', data: { chart: null, data: [] }, mounted() { this.chart = echarts.init(this.$refs.chart); this.getData(); }, methods: { getData() { fetch('api.php') // Call PHP API .then(response => response.json()) .then(data => { this.data = data; this.updateChart(); }); }, updateChart() { // Update chart data and re-render const option = { // Chart configuration series: [{ data: this.data }] }; this.chart.setOption(option); } } }); </script>
In this code, the Vue instance contains a div element for displaying the chart. The ECharts instance is initialized in the mounted lifecycle hook, and the getData method fetches JSON data from the PHP API. The updateChart method updates the chart accordingly.
To enable real-time chart updates, you can use a timer to periodically call the getData method.
setInterval(() => { this.getData(); }, 5000); // Update data every 5 seconds
This code calls getData every 5 seconds, refreshing the chart and ensuring that the displayed data remains up-to-date.
This article demonstrated how to combine PHP and Vue.js to achieve real-time data updates in charts. By providing a PHP data API and using Vue.js with ECharts on the frontend, developers can easily create dynamic, real-time visualizations. This approach is flexible, easy to understand, and suitable for various types of data chart applications.