Home  >  Article  >  Backend Development  >  PHP and Vue.js example tutorial: How to use statistical charts to display sales data

PHP and Vue.js example tutorial: How to use statistical charts to display sales data

WBOY
WBOYOriginal
2023-08-17 08:39:211453browse

PHP and Vue.js example tutorial: How to use statistical charts to display sales data

PHP and Vue.js example tutorial: How to use statistical charts to display sales data

Introduction:
In the process of website or application development, it is often necessary to display Data, especially sales data. Statistical charts can clearly present data trends and key indicators, providing us with a more intuitive way to understand and analyze data. This article will introduce how to use PHP and Vue.js to create statistical charts and display sales data.

1. Preparation
Before starting the tutorial, we need to prepare some basic knowledge and tools:
1. Install the PHP environment and MySQL database.
2. Install Vue.js, Vue CLI and related dependencies.

2. Back-end development

  1. Create database
    First, we need to create a table in the MySQL database to store sales data. You can use the following SQL statement to create a table named "sales_data":

    CREATE TABLE sales_data (
      id INT PRIMARY KEY AUTO_INCREMENT,
      date DATE,
      amount DECIMAL(10,2),
      product_id INT
    );

    This table has four fields: id, date, amount and product_id.

  2. Create PHP interface
    Next, we need to create a PHP interface to handle CRUD operations of data (create, read, update and delete). Create a folder named "api" in the project directory and create a file named "sales.php" in it. Copy the following code into "sales.php":

    <?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json");
    
    include_once 'config/database.php';
    include_once 'objects/sales.php';
    
    $database = new Database();
    $db = $database->getConnection();
    
    $sales = new Sales($db);
    
    $request_method = $_SERVER["REQUEST_METHOD"];
    
    // 处理GET请求
    if($request_method == 'GET'){
     $data = $sales->getSalesData();
     echo json_encode($data);
    } 
    // 处理POST请求
    else if($request_method == 'POST'){
     $data = json_decode(file_get_contents("php://input"));
    
     $sales->date = $data->date;
     $sales->amount = $data->amount;
     $sales->product_id = $data->product_id;
    
     if($sales->createSalesData()){
         echo json_encode("Sales data was created.");
     } else{
         echo json_encode("Unable to create sales data.");
     }
    }
    ?>

    The above code creates a "Sales" class for handling CRUD operations on sales data. The interface supports GET and POST requests.

  3. Create database connection and Sales class
    Create a file named "database.php" in the "config" folder and copy the following code into it:

    <?php
    class Database{
     
     private $host = "localhost";
     private $db_name = "your_database_name";
     private $username = "your_username";
     private $password = "your_password";
     public $conn;
     
     public function getConnection(){
     
         $this->conn = null;
     
         try{
             $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
             $this->conn->exec("set names utf8");
         }catch(PDOException $exception){
             echo "Connection error: " . $exception->getMessage();
         }
     
         return $this->conn;
     }
    }
    ?>

    Replace "your_database_name", "your_username" and "your_password" with your database name, username and password.

Next, create a file named "sales.php" in the "objects" folder and copy the following code into it:

<?php
class Sales{
 
    private $conn;
    private $table_name = "sales_data";
 
    public $id;
    public $date;
    public $amount;
    public $product_id;
 
    public function __construct($db){
        $this->conn = $db;
    }
 
    function getSalesData(){
        $query = "SELECT date, SUM(amount) as amount FROM " . $this->table_name . " GROUP BY date";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
 
        return $stmt;
    }
 
    function createSalesData(){
        $query = "INSERT INTO " . $this->table_name . " SET date=:date, amount=:amount, product_id=:product_id";
        $stmt = $this->conn->prepare($query);
 
        $this->date=htmlspecialchars(strip_tags($this->date));
        $this->amount=htmlspecialchars(strip_tags($this->amount));
        $this->product_id=htmlspecialchars(strip_tags($this->product_id));
 
        $stmt->bindParam(":date", $this->date);
        $stmt->bindParam(":amount", $this->amount);
        $stmt->bindParam(":product_id", $this->product_id);
 
        if($stmt->execute()){
            return true;
        }
 
        return false;
    }
}
?>

This paragraph The code defines a "Sales" class and contains methods for obtaining sales data and creating sales data.

3. Front-end development

  1. Create Vue.js project
    Open the command line and navigate to your project directory. Run the following command to create a new Vue.js project:

    vue create sales-chart

    Select the corresponding configuration items according to the wizard and wait for the project to be created.

  2. Install chart.js
    Execute the following command in the project directory to install chart.js:

    npm install chart.js
  3. Write page code
    Open the "App.vue" file in the "src" folder, and copy the following code into it:

    <template>
      <div id="app">
     <canvas id="chart"></canvas>
      </div>
    </template>
    
    <script>
    import Chart from 'chart.js';
    
    export default {
      mounted() {
     this.createChart();
      },
      methods: {
     createChart() {
       fetch('http://localhost/api/sales.php')
         .then(response => response.json())
         .then(data => {
           const chartData = {
             labels: [],
             datasets: [
               {
                 label: '销售额',
                 data: [],
                 backgroundColor: 'rgba(54, 162, 235, 0.2)',
                 borderColor: 'rgba(54, 162, 235, 1)',
                 borderWidth: 1,
               },
             ],
           };
    
           data.forEach(row => {
             chartData.labels.push(row.date);
             chartData.datasets[0].data.push(row.amount);
           });
    
           new Chart(document.getElementById('chart'), {
             type: 'line',
             data: chartData,
             options: {
               scales: {
                 yAxes: [{
                   ticks: {
                     beginAtZero: true,
                   },
                 }],
               },
             },
           });
         });
     },
      },
    };
    </script>
    
    <style>
    #chart {
      width: 600px;
      height: 400px;
    }
    </style>

    In the above code, we first introduced the chart.js library, and in the mounted function Call the createChart function. In the createChart function, the sales data is obtained from the PHP interface through the fetch method and a chart is created based on the data.

4. Run the project
Finally, run the following command to start the Vue.js project:

npm run serve

Visit http://localhost:8080 in the browser, You can see statistical charts showing sales data.

Summary:
This article details how to use PHP and Vue.js to create statistical charts and display sales data. Through this example tutorial, you can learn how to use PHP to provide interfaces on the back end, and use Vue.js and chart.js libraries on the front end to create charts. I hope this article is helpful to you, thank you for reading!

The above is the detailed content of PHP and Vue.js example tutorial: How to use statistical charts to display sales data. 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