PHP and Vue.js practical skills: how to display market trend data through statistical charts

王林
Release: 2023-08-19 08:16:01
Original
806 people have browsed it

PHP and Vue.js practical skills: how to display market trend data through statistical charts

PHP and Vue.js practical skills: How to display market trend data through statistical charts

Market trend data is very important to both companies and investors and can help They make smart decisions. Displaying these data through statistical charts can make trends more intuitive and easy to understand. In this article, we will introduce how to use PHP and Vue.js, two popular development tools, to achieve this functionality.

1. Data preparation
First, we need to prepare some sample data to show market trends. Suppose we have a stock market data set that contains dates and stock indices. We store the data in a database table named market_trend, including two fields: date and index. We can create the table and insert some sample data through the following SQL statement:

CREATE TABLE market_trend (
    date DATE,
    index FLOAT
);

INSERT INTO market_trend (date, index) VALUES
    ('2021-01-01', 100),
    ('2021-01-02', 110),
    ('2021-01-03', 120),
    ('2021-01-04', 105),
    ('2021-01-05', 95),
    ('2021-01-06', 115),
    ('2021-01-07', 125),
    ('2021-01-08', 130);
Copy after login

2. Backend development
Next, we use PHP to write the backend program, which will get the market from the database Trend data. We use PDO to connect to the database and write a simple function to execute the query and return the results. The following is the sample code of the getData() function:

<?php
function getData() {
    $host = 'localhost';
    $dbname = 'your_database';
    $username = 'your_username';
    $password = 'your_password';

    $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ];

    try {
        $pdo = new PDO($dsn, $username, $password, $options);
    } catch (PDOException $e) {
        die("Connection failed: " . $e->getMessage());
    }

    try {
        $query = $pdo->prepare("SELECT * FROM market_trend");
        $query->execute();

        return $query->fetchAll();
    } catch (PDOException $e) {
        die("Query failed: " . $e->getMessage());
    }
}
?>
Copy after login

3. Front-end development
In the front-end part, we will use Vue.js to build a simple page to display market trends data. We need to introduce the CDN link of Vue.js and write a Vue instance to process data and render charts. The following is an example HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Market Trend</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.bundle.min.js"></script>
    <style>
        canvas {
            max-width: 800px;
        }
    </style>
</head>
<body>
    <div id="app">
        <canvas id="chart"></canvas>
    </div>

    <script>
        var app = new Vue({
            el: '#app',
            mounted: function () {
                this.getData();
            },
            methods: {
                getData: function () {
                    // 调用后端接口获取数据
                    // 此处使用axios示例,你可以根据实际情况选择适合的方式
                    axios.get('backend.php')
                        .then(function (response) {
                            // 处理返回的数据
                            var data = response.data;

                            // 构造图表数据
                            var dates = [];
                            var indices = [];

                            data.forEach(function (item) {
                                dates.push(item.date);
                                indices.push(item.index);
                            });

                            // 使用Chart.js绘制图表
                            var ctx = document.getElementById('chart').getContext('2d');
                            var chart = new Chart(ctx, {
                                type: 'line',
                                data: {
                                    labels: dates,
                                    datasets: [{
                                        label: 'Market Trend',
                                        data: indices,
                                        backgroundColor: 'rgba(0, 123, 255, 0.4)',
                                        borderColor: 'rgba(0, 123, 255, 0.8)',
                                        borderWidth: 1
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    maintainAspectRatio: false,
                                    scales: {
                                        yAxes: [{
                                            ticks: {
                                                beginAtZero: false
                                            }
                                        }]
                                    }
                                }
                            });
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                }
            }
        });
    </script>
</body>
</html>
Copy after login

In the above code, we first introduced the CDN links for Vue.js and Chart.js. Then, we wrote a Vue instance and used the mounted hook function to call the getData() method to obtain market trend data when the page is loaded. In the getData() method, we use the axios library to call the backend interface, and use Chart.js to draw the chart after obtaining the data.

Through the above code example, we can view charts showing market trend data in the browser. Of course, you need to fill in the actual backend API address into axios.get('backend.php') in order to get the real data from the database.

Summary
This article introduces how to use PHP and Vue.js to implement the function of displaying market trend data through statistical charts. Through this example, you can learn how to use PHP on the backend to connect to the database and write a simple function to get the data. At the same time, by using Vue.js and Chart.js on the front end, we can visualize the data into intuitive statistical charts. I hope this article can help you implement similar functions during the development process.

The above is the detailed content of PHP and Vue.js practical skills: how to display market trend data through statistical charts. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!