Home  >  Article  >  Backend Development  >  How to use PHP and Vue to implement data connection function

How to use PHP and Vue to implement data connection function

王林
王林Original
2023-09-24 18:49:412020browse

How to use PHP and Vue to implement data connection function

How to use PHP and Vue to implement data connection function

Introduction:
In modern web applications, data connection is a very important function. Interacting the data on the backend with the user interface on the frontend is key to achieving a user-friendly application. PHP is a popular server-side programming language, while Vue is a popular front-end framework. Data connection functionality can be easily implemented using PHP and Vue together. In this article, we will focus on how to use PHP and Vue to implement data connection functions and provide specific code examples.

1. Create a database
First, we need to create a database to store our data. MySQL or other relational database management systems can be used. The following is a sample SQL query to create a database named "students" and a data table named "users":

CREATE DATABASE students;
USE students;

CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255),
  email VARCHAR(255),
  age INT
);

2. Create a PHP backend
Next, we need to create a PHP The backend handles interaction with the database. We can use PHP's PDO (PHP Data Objects) extension to connect and perform database-related operations. The following is a simple PHP backend code example for getting and saving user data:

<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=students', 'username', 'password');

// 获取用户数据
function getUsers() {
  global $db;
  $query = $db->query('SELECT * FROM users');
  $users = $query->fetchAll(PDO::FETCH_ASSOC);
  return $users;
}

// 保存用户数据
function saveUser($name, $email, $age) {
  global $db;
  $stmt = $db->prepare('INSERT INTO users (name, email, age) VALUES (?, ?, ?)');
  $stmt->execute([$name, $email, $age]);
}

3. Create a Vue frontend
Now, let us create a Vue frontend to display and save user data. We can use the axios library provided by Vue to send HTTP requests to the backend and bind data to the front-end interface. The following is a simple Vue front-end code example:

<template>
  <div>
    <h1>用户列表</h1>
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.name }} - {{ user.email }} - {{ user.age }}
      </li>
    </ul>
    <h2>添加用户</h2>
    <input v-model="name" placeholder="姓名" />
    <input v-model="email" placeholder="邮箱" />
    <input v-model="age" placeholder="年龄" />
    <button @click="saveUser">保存</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: [],
      name: '',
      email: '',
      age: ''
    };
  },
  mounted() {
    this.getUsers();
  },
  methods: {
    getUsers() {
      axios.get('backend.php?action=getUsers')
        .then(response => {
          this.users = response.data;
        })
        .catch(error => {
          console.error(error);
        });
    },
    saveUser() {
      axios.post('backend.php?action=saveUser', {
        name: this.name,
        email: this.email,
        age: this.age
      })
      .then(() => {
        this.getUsers();
        this.name = '';
        this.email = '';
        this.age = '';
      })
      .catch(error => {
        console.error(error);
      });
    }
  }
};
</script>

4. Connect the front-end and back-end
Finally, we need to connect the front-end and back-end. We can create a file named "backend.php" to handle HTTP requests sent by the front end and call the corresponding backend functions. The following is a simple "backend.php" code example:

<?php
header('Content-Type: application/json');

include 'db.php';

$action = $_GET['action'];

if ($action === 'getUsers') {
  $users = getUsers();
  echo json_encode($users);
}

if ($action === 'saveUser') {
  $name = $_POST['name'];
  $email = $_POST['email'];
  $age = $_POST['age'];
  saveUser($name, $email, $age);
}

Now, when we access the Vue front-end page in the browser, it will send an HTTP request to the PHP backend through axios and bind the data Set to the front-end interface. When we fill the form and click the "Save" button, it will send an HTTP POST request to the backend and save the user data to the database.

Conclusion:
By using PHP and Vue, we can easily implement the data connection function. PHP provides tools for interacting with the database, while Vue provides a flexible and easy-to-use front-end framework. By connecting the front-end and back-end, we can build user-friendly applications and enable operations on data. Through the introduction and code examples of this article, I believe readers have a basic understanding of how to use PHP and Vue to implement data connection functions.

The above is the detailed content of How to use PHP and Vue to implement data connection function. 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