Mysql Delete Data in PHP
To delete data from a MySQL database using MySQLi in PHP, you need to:
Connect to the database.
Write an SQL
DELETEquery to remove the data.Execute the query.
Check if the deletion was successful.
Here’s an example that shows how to delete data from a table using MySQLi in both procedural and object-oriented approaches.
1. Delete Data Using MySQLi (Procedural Approach)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = mysqli_connect($host, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}// SQL query to delete a record$sql = "DELETE FROM users WHERE id = 1"; // Example: delete the user with id = 1// Execute the queryif (mysqli_query($conn, $sql)) { echo "Record deleted successfully.";} else { echo "Error deleting record: " . mysqli_error($conn);}// Close the connectionmysqli_close($conn);?>2. Delete Data Using MySQLi (Object-Oriented Approach)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = new mysqli($host, $username, $password, $dbname);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}// SQL query to delete a record$sql = "DELETE FROM users WHERE id = 1"; // Example: delete the user with id = 1// Execute the queryif ($conn->query($sql) === TRUE) { echo "Record deleted successfully.";} else { echo "Error deleting record: " . $conn->error;}// Close the connection$conn->close();?>Explanation:
Database Connection:
In both approaches, we connect to the database using the MySQLi connection function
mysqli_connect()(procedural) ornew mysqli()(object-oriented).If the connection fails, an error message is displayed.
SQL DELETE Query:
The SQL
DELETEquery removes a row from theuserstable where theidis equal to 1.You can modify the condition in the
WHEREclause to delete other specific records.
Execute the Query:
We use
mysqli_query()(procedural) or$conn->query()(object-oriented) to execute the query.If the query is successful, a success message is displayed. Otherwise, an error message is shown.
Close the Connection:
After performing the operation, it’s important to close the connection to the database using
mysqli_close()(procedural) or$conn->close()(object-oriented).
Notes:
DELETE queries are irreversible. Once data is deleted, it cannot be undone unless you have backups or transaction handling in place.
You can use conditions in the
WHEREclause to delete specific rows. If no condition is provided, all rows in the table will be deleted (be cautious when doing this).
Let me know if you need any additional clarifications or adjustments!