PHP : MySQL DELETE Statement
The DELETE statement removes records from a table. You choose which rows to remove with the WHERE clause.
Syntax
DELETE FROM table_name WHERE condition;
Note:
Always use WHERE. Without it, DELETE FROM users removes every row of the table. A deleted record can not be taken back, so keep a database backup.
Delete a record using PHP
<?php
require_once('db-connection.php');
// Delete the user with id 3
$sql = "DELETE FROM users WHERE id = 3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted. Rows deleted: " . mysqli_affected_rows($conn);
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Tutorials Class - Output Window
Record deleted. Rows deleted: 1
mysqli_affected_rows() shows how many rows were removed. If no row matches the condition, the query still works, but the number is 0.
Delete with a prepared statement
The id usually comes from a link or a button, for example delete.php?id=3. Never put it directly in the query. Use a prepared statement.
<?php
require_once('db-connection.php');
$id = (int) ($_GET["id"] ?? 0);
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
echo "Rows deleted: " . $stmt->affected_rows;
$stmt->close();
$conn->close();
?>
Output:
For delete.php?id=3 when the user exists
Rows deleted: 1
A delete action should be a POST request with a CSRF token, not a simple link, because a link can be opened by anyone or by a bot. See CSRF.
DELETE, TRUNCATE and DROP
| Command | What it does |
|---|---|
| DELETE FROM users WHERE … | Removes the selected rows. The table stays |
| TRUNCATE TABLE users | Removes all rows quickly and resets the AUTO_INCREMENT counter |
| DROP TABLE users | Removes the whole table, with its structure |
In many websites the data is not really deleted. A column like is_deleted is set to 1 instead, so the record can be restored later. This is called a soft delete.
Summary
- DELETE removes records, WHERE selects which ones.
- Never run DELETE without WHERE.
- Use prepared statements when the id comes from the user.
- Go back to the PHP MySQL Tutorial index.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |