Delete Data from MySQL Database in React Js With AXIOS || React CRUD Using PHP API and MySQL -07
When building a web application, it’s common to need to delete data from a MySQL database using React Js with AXIOS. This is typically done through a PHP API that interacts with the database. In this article, we’ll cover how to implement this functionality.
Prerequisites
Before getting started, make sure you have the following:
- Basic knowledge of React Js
- A working MySQL database
- PHP installed on your server
- AXIOS library installed in your React Js project
Implementation
First, let’s create a PHP API that will handle the deletion of data from the MySQL database. Create a file called delete.php and add the following code:
<?php
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$sql = "DELETE FROM your_table_name WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Next, we’ll create a React Js component that will use AXIOS to send a DELETE request to the PHP API. In your React Js project, create a component called DeleteData.js and add the following code:
import React from 'react';
import axios from 'axios';
class DeleteData extends React.Component {
constructor(props) {
super(props);
this.state = {
id: 1 // initialize with some default value
};
}
handleDelete = () => {
const { id } = this.state;
axios.delete(`http://your_domain/delete.php?id=${id}`)
.then(response => {
console.log(response.data);
// Handle successful deletion
})
.catch(error => {
console.error(error);
// Handle error
});
}
render() {
return (
<button onClick={this.handleDelete}>Delete Data</button>
)
}
}
export default DeleteData;
Finally, you can use the DeleteData component in your application wherever you need to delete data from the MySQL database. When the button is clicked, it will send a DELETE request to the PHP API, which will then delete the corresponding record from the database.
Conclusion
In this article, we covered how to delete data from a MySQL database using React Js with AXIOS. By creating a PHP API to handle the database interaction and using AXIOS to send requests from the React Js component, you can easily implement CRUD functionality in your web application.
Your video best of the best ❤🎉 thank you for that, this is greatest tutorial ever I seen)))🎉
Please make React CRUD and upload image with Form submit.
hello sir, aap koi app mvc pattern per banaye aur isme react, nodejs, mysql, express ka use kare, thank u –(Abhishek sharma)
Email Kiya Hai But Avi Tak No Reply
Kya Hua Bhai Jaan