Insert Data in PHP using Vue.js
In this blog post, we’ll explore how to integrate Vue.js with PHP to insert data into a MySQL database seamlessly. This approach is perfect for web developers who want to build dynamic, data-driven applications with a modern front-end framework and a reliable server-side language.
Setting Up Your Environment
Before diving into coding, let’s set up your development environment to ensure everything runs smoothly.
1. Folder Structure
Organize your project with a clear structure. Create a root directory for your project and within it, place the following files:
/project-root /config.php /insert.php /index.html
2. Create the Database
To begin, you’ll need to create a MySQL database where your data will be stored.
- Open your web browser and navigate to http://localhost/phpmyadmin/. This is the interface for managing your MySQL databases.
- Click on “Databases” and create a new database named vue_data.
- Select the vue_data database and run the following SQL query to create a table named student:
CREATE TABLE `student` ( `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` TEXT NOT NULL, `email` TEXT NOT NULL, `message` TEXT NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Note: This query sets up a table with an auto-incrementing primary key and three fields for storing user data.
Creating the Configuration File
The config.php file will handle your database connection settings. Here’s how to set it up:
- Create config.php
- Copy this code and paste it into your file.
<?php // Database credentials define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_NAME', 'vue_data'); // Attempt to connect to the database $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } ?>
Note: In your project root directory, create a file named config.php and add the following code. This script defines your database credentials and establishes a connection using the MySQLi extension. If the connection fails, it will output an error message.
Creating the Insertion Script
The insert.php file will handle data submission from your front end and insert it into the database.
- Create insert.php
- Copy this code and paste it into your file
<?php // Include database configuration require "config.php"; // Get POST data $data = json_decode(file_get_contents("php://input")); // Escape special characters to prevent SQL injection $name = mysqli_real_escape_string($link, $data->name); $email = mysqli_real_escape_string($link, $data->email); $message = mysqli_real_escape_string($link, $data->message); // Validate input data if($name != "" && $email != "" && $message != ""){ $sql = "INSERT INTO student (name, email, message) VALUES ('$name', '$email', '$message')"; $run = mysqli_query($link, $sql); if($run){ echo "Data Inserted Successfully"; } else { echo "Error inserting data: " . mysqli_error($link); } } else { echo "All fields are required!"; } // Close the database connection mysqli_close($link); ?>
Note: Create a file named insert.php in your project root and add the following code. This script reads JSON data sent via POST, sanitizes it to prevent SQL injection, and inserts it into the student table. It also checks for required fields and handles errors gracefully.
Creating the HTML & Vue.js Code
The index.html file will provide the user interface and handle interactions using Vue.js.
- Create index.html
- Copy this code and paste it into your file
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/> <title>Vue.js Data Insertion</title> </head> <body> <!-- INSERT DATA FORM --> <div class="container my-5" id="app" style="width:660px;"> <h1 class="text-center">Vue.js Data Insertion</h1> <div class="mb-3"> Name: <input type="text" class="form-control my-2" v-model="name"> Email Address: <input type="email" class="form-control my-2" v-model="email"> Message: <textarea class="form-control my-2" rows="3" v-model="message"></textarea> <button type="button" class="btn btn-primary mt-5" v-on:click="submitForm">Submit</button> </div> </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> const app = Vue.createApp({ data() { return { name: '', email: '', message: '', } }, methods: { submitForm() { axios.post('insert.php', { name: this.name, email: this.email, message: this.message }) .then(response => { // Handle successful response alert(response.data); this.name = ''; this.email = ''; this.message = ''; }) .catch(error => { // Handle error response console.error("There was an error!", error); }); } } }); app.mount('#app'); </script> </body> </html>
Note: Create a file named index.html and add the following content, This HTML file sets up a form for user input and uses Vue.js to manage form data and submit it using Axios. The form fields are bound to Vue.js data properties, and the submitForm method sends a POST request to insert.php.
Conclusion
By following these steps, you’ve learned how to set up a system for inserting data into a MySQL database using PHP and Vue.js. This method allows for a clean separation of concerns, where Vue.js handles the front-end interactions and PHP manages server-side processing. This setup not only enhances your web application’s functionality but also ensures a smooth user experience.
Feel free to modify and expand on this example to fit your specific needs. Happy coding!