Chart visualization is a highly practical feature in today’s web development, helping users intuitively understand and analyze various data. This article walks you through how to use PHP and Vue.js together with ECharts to achieve efficient chart displays.
ECharts is a powerful and easy-to-use open-source charting library supporting various chart types and interactive features. You can include ECharts via CDN or download it locally, making it flexible for different project requirements.
Use PHP to create a backend API that connects to the database with PDO, queries data, and returns it in JSON format for the frontend. Here's an example:
<?php // Connect to database $dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $username = 'root'; $password = ''; $db = new PDO($dsn, $username, $password); // Query data $sql = 'SELECT * FROM data'; $stmt = $db->query($sql); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); // Return data header('Content-Type: application/json'); echo json_encode($data); ?>
This code shows how to connect to the database, execute a query, and output the result as JSON for the frontend to consume.
On the frontend, use Vue.js to build the UI, axios to fetch data from the PHP API, and ECharts to initialize and render the chart. Example code:
<template> <div id="app"> <div id="chart" style="width: 600px; height: 400px;"></div> </div> </template> <script> import echarts from 'echarts'; import axios from 'axios'; export default { mounted() { // Send HTTP request to get data axios.get('/api/data.php') .then(response => { const data = response.data; // Initialize chart const chart = echarts.init(document.getElementById('chart')); const options = { // Configure chart type and style based on data // Example configuration can be customized xAxis: { type: 'category', data: data.map(item => item.name) // assuming data has 'name' field }, yAxis: { type: 'value' }, series: [{ data: data.map(item => item.value), // assuming data has 'value' field type: 'bar' }] }; chart.setOption(options); }) .catch(error => { console.error(error); }); } } </script>
This Vue component automatically fetches data and renders a dynamic chart once the page loads, reflecting the backend data content.
Combining PHP and Vue.js to implement chart display effectively presents backend data visually through modern frontend technologies, enhancing user experience. ECharts, as a powerful chart library, supports a variety of chart types and rich interactions, making it an ideal choice for such features. We hope this guide helps you quickly build your own dynamic data charts.