Home > Article > Backend Development > How to implement data deletion function using PHP and Vue
How to use PHP and Vue to implement the data deletion function
Introduction:
In Web development, adding, deleting, modifying and checking data is a common operation. This article will introduce in detail how to implement the data deletion function through the combination of PHP and Vue, including the writing of front-end Vue and the processing of back-end PHP.
1. Front-end implementation
<script>export default {<br> methods: {</script>
deleteData() { // 在这里触发删除事件 }
}
}
npm install axios
Next, introduce axios in DeleteButton.vue and send the request in the delete method. Assume that our deletion interface is delete.php, which needs to receive an id parameter as the identification of the data to be deleted.
<script><br>import axios from 'axios';</script>
export default {
methods: {
deleteData() { const id = 1; // 假设需要删除的数据的id为1 axios.delete('delete.php', { params: { id: id } }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); }
}
}
2. Back-end implementation
$id = $_GET['id']; // Get the id parameter passed by the front end
// Add and delete data here Logic
//Return response
$response = [
'status' => 'success',
'message' => 'Delete successfully'
];
header('Content-Type: application/json');
echo json_encode($response);
?>
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test ";
$id = $_GET['id']; // Get the id parameter passed by the front end
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error );
}
//Delete data
$sql = "DELETE FROM users WHERE id = ${id}";
if ($conn->query( $sql) === TRUE) {
$response = [
'status' => 'success', 'message' => '删除成功'
];
} else {
$response = [
'status' => 'error', 'message' => '删除失败'
];
}
$conn->close();
header('Content-Type: application/json');
echo json_encode($response);
?> ;
Summary:
Through Vue's front-end components and axios plug-in, we can easily communicate with the back-end to realize the data deletion function. The backend uses PHP to connect to the database and perform data deletion operations based on the parameters passed by the frontend. This combination can effectively improve development efficiency and ensure data security.
The above is the detailed content of How to implement data deletion function using PHP and Vue. For more information, please follow other related articles on the PHP Chinese website!