Delete Data in PHP using Vue.js
In this blog post, we’ll explore the process of effortlessly deleting data from a MySQL database using PHP and Vue.js. By following these steps, you’ll be able to seamlessly integrate Vue.js with PHP and efficiently manage data deletion in your web applications, ensuring a dynamic and responsive user experience. / Delete Data in PHP using Vue.js
Setting Up Your Environment
Before we dive into coding, it’s essential to ensure that your development environment is set up correctly. This will allow all the components to work together smoothly and efficiently.
1. Folder Structure
Begin by organizing your project files into a clear and logical structure. Here’s an example structure for this tutorial:
/project-root /config.php /fetch.php /delete.php /index.html
Note: This structure helps keep your configuration, data-fetching logic, deletion logic, and front-end code neatly organized and easy to manage.
2. Create the Database
The first step in our setup is to create a MySQL database where the 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.
- After creating the database, select it and run the following SQL query to create a student table:
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 table will store the student records, including their ID, name, email, and message.
3. Add Data to the Database
To work with data deletion, we first need to populate the student table with some sample data. Insert the following data into the table:
INSERT INTO `student` (`id`, `name`, `email`, `message`) VALUES (1, 'Sachin', '[email protected]', 'Hey, I am Sachin'), (2, 'Ankit', '[email protected]', 'Hey Ankit'), (3, 'Tina', '[email protected]', 'Hey, I am Tina'), (4, 'Rohit', '[email protected]', 'Hello, I am Rohit');
Note: This SQL query adds four records to the student table, which we’ll later use to demonstrate data deletion.
Creating the Configuration File
The config.php file will handle the 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 establishes a connection to your MySQL database using the MySQLi extension. If the connection fails, the script will terminate and output an error message.
Creating the Fetch Script
The fetch.php script will retrieve the data from the MySQL database and return it as a JSON response to the front end.
- Create fetch.php
- Copy this code and paste it into your file.
<?php // Include database configuration require "config.php"; $output = array(); $query = "SELECT * FROM student"; $result = mysqli_query($link, $query); while($row = mysqli_fetch_array($result)) { $output[] = $row; } echo json_encode($output); // Close the database connection mysqli_close($link); ?>
Note: Create a file named fetch.php in your project root directory and add the following code, This script queries the student table, fetches all rows, and encodes them into a JSON format. The mysqli_fetch_array function retrieves each row as an associative array, making it easy to handle in JavaScript.
Creating the Delete Script
The delete.php script will handle the deletion of data from the MySQL database based on the ID provided from the front end.
- Create delete.php
- Copy this code and paste it into your file.
<?php // Include database configuration require "config.php"; // Get the posted data $data = json_decode(file_get_contents("php://input")); $id = $data->id; // Prepare and execute the delete query $query = "DELETE FROM student WHERE id='$id'"; if(mysqli_query($link, $query)) { echo 'Data Deleted'; } else { echo 'Error'; } // Close the database connection mysqli_close($link); ?>
Note: Create a file named delete.php in your project root directory and add the following code,
This script deletes the record from the student table where the id matches the one sent from the front end. If the deletion is successful, it returns a confirmation message; otherwise, it returns an error message.
Creating the HTML & Vue.js Code
The index.html file will serve as the front end of your application, allowing users to view the data and delete records.
- 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 CRUD - Delete Data</title> </head> <body> <div class="container my-5" id="app" style="width:660px;"> <h1 class="text-center">Vue.js CRUD - Delete Data</h1> <!-- DISPLAY DATA HERE --> <h1>Data Records</h1> <table class="table"> <thead> <tr> <th scope="col">ID</th> <th scope="col">NAME</th> <th scope="col">EMAIL</th> <th scope="col">MESSAGE</th> <th scope="col">Update</th> <th scope="col">Delete</th> </tr> </thead> <tbody> <tr v-for="student in students" :key="student.id"> <th>{{ student.id }}</th> <td>{{ student.name }}</td> <td>{{ student.email }}</td> <td>{{ student.message }}</td> <td><button type="button" class="btn btn-warning btn-sm" v-on:click="update(student.id)" data-bs-toggle="modal" data-bs-target="#exampleModal">Update</button></td> <td><button type="button" class="btn btn-danger btn-sm" v-on:click="deletee(student.id)">Delete</button></td> </tr> </tbody> </table> </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 { students: [], } }, mounted() { this.fetchData(); }, methods: { // Fetch All Data fetchData() { axios.get('fetch.php') .then(response => { this.students = response.data; }) .catch(error => { console.error('Error fetching data:', error); }); }, // Delete Single Data deletee(id) { if (confirm("Do you want to delete this data?")) { axios.post('delete.php', { id: id }) .then(response => { console.log(response.data); this.fetchData(); // Refresh student records after successful deletion }) .catch(error => { console.error('Error deleting data:', error); }); } else { console.log("You canceled!"); } } } }); app.mount('#app'); </script> </body> </html>
Note: Create a file named index.html and add the following content,
This HTML file features a Bootstrap-styled table that displays data fetched from the MySQL database. Vue.js handles data binding, while Axios is used to make the GET request to fetch.php for retrieving data and the POST request to delete.php for deleting data. When the page loads, the fetchData method is called to populate the table with data from the database. The deletee method is linked to the delete button, triggering the deletion process upon confirmation.
Read Also: Fetch Data in PHP using Vue.js
Conclusion
By following these steps, you’ve successfully created a basic CRUD application using Vue.js and PHP, focusing on data deletion. This approach enables efficient data management in your web applications, providing a seamless user experience with real-time updates. Continue exploring and expanding your knowledge to build more complex and robust applications.