Delete Data
How to Delete Data from MySQL in PHP Safely
To delete data from MySQL in PHP, run a prepared DELETE FROM statement through PDO, always with a strict WHERE condition and a check that the current user is allowed to remove that row. A delete is the one database operation you can't take back with a simple page refresh. A single missing WHERE clause can empty a whole table.
This guide shows a safe PDO delete function, explains soft deletes versus hard deletes, and covers the mistakes that most often cause lost data or security holes in real projects.
Delete Data from MySQL in PHP with a Prepared Statement
A prepared statement sends the SQL and the values separately, so user input can never change the structure of the query. For a delete, this means the row ID is bound as a parameter instead of being pasted into the SQL string.
Before the delete function, here is a typical PDO connection. Setting the error mode to exceptions matters, because it makes failed deletes (for example, foreign key violations) show up as catchable errors instead of silent failures.
<?php
declare(strict_types=1);
$pdo = new PDO(
'mysql:host=localhost;dbname=shop;charset=utf8mb4',
'db_user',
'db_password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
]
);Replace the host, database name, and credentials with your own, and keep real credentials out of version control.
Parameterized DELETE with Ownership Verification
When records belong to a user, bind both the row ID and the owner's ID in the WHERE clause. That way, a customer can't delete someone else's record just by guessing an ID.
<?php
declare(strict_types=1);
function deleteSavedAddress(PDO $pdo, int $addressId, int $ownerUserId): bool
{
$stmt = $pdo->prepare(
'DELETE FROM user_addresses WHERE id = :id AND user_id = :user_id LIMIT 1'
);
$stmt->execute([
':id' => $addressId,
':user_id' => $ownerUserId,
]);
return $stmt->rowCount() === 1;
}Three details make this function safer than a basic delete:
Both conditions are in the SQL. The ownership check happens inside the query itself, so there's no gap between "check" and "delete" for something to slip through.
LIMIT 1is a guardrail. The ID is normally unique, so only one row should match, butLIMIT 1caps the damage if a bug ever makes the condition broader than intended. MySQL supportsLIMITon single-tableDELETEstatements.The return value is meaningful.
rowCount()reports how many rows the statement deleted. A result of1means the record existed and belonged to this user. A result of0means nothing matched, either because the ID doesn't exist or because it belongs to someone else. You can't tell which, and that's a good thing: the response doesn't leak whether another user's record exists.
Soft Deletes vs. Hard Deletes
A hard delete removes the row for good. A soft delete keeps the row and marks it as deleted, usually with a deleted_at timestamp column.
UPDATE orders SET deleted_at = NOW() WHERE id = :id AND user_id = :user_id;For invoices, orders, and user-generated content tied to financial or audit history, prefer a soft delete. It keeps the trail intact, and an accidental deletion can be undone by setting deleted_at back to NULL. Hard deletes suit data with no long-term value, such as expired tokens, abandoned drafts, or records you must erase on request.
The extra work in that last row is the main trap with soft deletes. Every query that lists or counts records needs WHERE deleted_at IS NULL. If you forget it in one place, "deleted" items reappear. Some teams solve this with a database view or a shared query helper.
Also keep privacy rules in mind. If a person has the right to have their data erased (for example under GDPR), a soft-deleted row may not satisfy the request. In that case, you may need to hard-delete or anonymize the data, and your retention and backup policy matters too. Check the rules that apply to your project, since this article isn't legal advice.
How to Check That Your Delete Works
Run
SELECT * FROM user_addresses WHERE id = 5;in your database client to confirm the row exists before you test.Submit the form as the owner. The function should return
true, and the sameSELECTshould return no row.Submit it again with the same ID. This time
rowCount()is0, so the function returnsfalse.Log in as a different user and try to delete the first user's record by changing the ID. It should return
false, and the row should still exist.Open
delete-address.phpdirectly in the browser address bar (a GET request). You should see the 405 response, not a deletion.Remove or alter the CSRF token field in DevTools and submit. You should get the 403 response.
Common Mistakes to Avoid
Deleting via
GETlinks (<a href="delete.php?id=5">): Browser pre-fetchers or crawlers visiting links—or CSRF image tags—can triggerGETdeletes unintentionally. Always require aPOSTorDELETErequest protected by a CSRF token.Omitting a
WHEREclause: RunningDELETE FROM userswithoutWHEREerases every row in the table. AddLIMIT 1for single-record deletes as an extra guardrail.Ignoring foreign key errors: Attempting to hard-delete a parent
userreferenced by a restrictive foreign key ininvoicesthrows aPDOException(23000). Decide deliberately betweenON DELETE CASCADE, soft deletes, or archiving.
Frequently Asked Questions
What is the difference between DELETE and TRUNCATE TABLE?
DELETE removes selected rows inside a transaction and can be rolled back. TRUNCATE TABLE drops and recreates the entire table, resets AUTO_INCREMENT, and cannot be rolled back.
Why did $stmt->rowCount() return 0 on a DELETE?
No row matched the WHERE conditions (either the ID did not exist or the ownership user_id check did not match).
Should delete buttons in HTML use <a> links or <form method="POST">?
Always use a <form method="POST"> (with a CSRF token and confirmation prompt) so only intentional user actions mutate data.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.