Home > Backend Development > PHP Tutorial > How to use PHP and Vue to implement data adding function

How to use PHP and Vue to implement data adding function

王林
Release: 2023-09-25 08:20:02
Original
1016 people have browsed it

How to use PHP and Vue to implement data adding function

How to use PHP and Vue to implement the data adding function

When developing web applications, the data adding function is a very common and important function point. This article will introduce how to use PHP and Vue.js to implement the data adding function and provide specific code examples.

  1. Front-end preparation

First, we need to use Vue.js on the front-end to build the user interface. On the page, we can use a form to collect data entered by the user and submit the data through a button.

First, introduce the Vue.js library in HTML and create a Vue instance:

<!DOCTYPE html>
<html>
<head>
  <title>Data Adding with PHP and Vue</title>
</head>
<body>
  <div id="app">
    <form @submit.prevent="addData">
      <input type="text" v-model="name" placeholder="Name">
      <input type="text" v-model="email" placeholder="Email">
      <button type="submit">Add Data</button>
    </form>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script src="app.js"></script>
</body>
</html>
Copy after login

In the above code, we pass the v-model directive to input The value of the box is bound to the data attribute in the Vue instance, and the content entered by the user in the input box will be automatically updated to the corresponding data attribute of the Vue instance. The @submit.prevent directive is used to prevent the form's default submission behavior and call the addData method of the Vue instance.

  1. Backend preparation

Next, we need to use PHP to process the data passed by the front end and store it in the database.

First, create a PHP file on the server, such as add_data.php. In this file, we need to receive the data sent by the front end and store it in the database.

<?php
// 连接到数据库
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// 获取前端传递过来的数据
$name = $_POST['name'];
$email = $_POST['email'];

// 将数据存储到数据库中
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
  echo "Data added successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Copy after login

In the above code, we first connect to the database and obtain the data passed by the front end. We then use the INSERT INTO statement to insert data into the users table of the database.

  1. Vue instance

Now, we need to write code in the Vue instance to handle the adding operation of data. First, create a JavaScript file named app.js in the root directory of the front-end project. In this file, we need to create a Vue instance and define the addData method to handle form submission.

new Vue({
  el: '#app',
  data: {
    name: '',
    email: ''
  },
  methods: {
    addData() {
      // 使用axios库发送POST请求
      axios.post('add_data.php', {
        name: this.name,
        email: this.email
      })
      .then(function (response) {
        console.log(response.data);
        // 清空输入框
        this.name = '';
        this.email = '';
      })
      .catch(function (error) {
        console.log(error);
      });
    }
  }
});
Copy after login

In the above code, we use the axios library to send a POST request to the add_data.php file on the server, and send the data that needs to be added as the request body. In the success callback function, we print out the response data returned by the server and clear the input box.

  1. Run the project

Now, we can run the project on the server. Place the above frontend and backend files in a directory and start a PHP server from the command line.

php -S localhost:8000
Copy after login

Then, visit http://localhost:8000 in the browser to see the form interface. Fill in the corresponding data in the input box and click the "Add Data" button. The data will be added to the database and "Data added successfully" will be displayed on the console.

Summary:

Through the above steps, we successfully implemented the data adding function using PHP and Vue.js. The front-end code uses Vue.js to build the user interface, and sends a POST request to the back-end PHP file through the axios library for data addition operations. The back-end PHP file receives the data sent by the front-end and stores it in the database. This method is simple and convenient and can be widely used when developing web applications.

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