Lesson

Delete Data

10 min reading
Free Course

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 1 is a guardrail. The ID is normally unique, so only one row should match, but LIMIT 1 caps the damage if a bug ever makes the condition broader than intended. MySQL supports LIMIT on single-table DELETE statements.

  • The return value is meaningful. rowCount() reports how many rows the statement deleted. A result of 1 means the record existed and belonged to this user. A result of 0 means 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

  1. Run SELECT * FROM user_addresses WHERE id = 5; in your database client to confirm the row exists before you test.

  2. Submit the form as the owner. The function should return true, and the same SELECT should return no row.

  3. Submit it again with the same ID. This time rowCount() is 0, so the function returns false.

  4. 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.

  5. Open delete-address.php directly in the browser address bar (a GET request). You should see the 405 response, not a deletion.

  6. Remove or alter the CSRF token field in DevTools and submit. You should get the 403 response.

Common Mistakes to Avoid

  • Deleting via GET links (<a href="delete.php?id=5">): Browser pre-fetchers or crawlers visiting links—or CSRF image tags—can trigger GET deletes unintentionally. Always require a POST or DELETE request protected by a CSRF token.

  • Omitting a WHERE clause: Running DELETE FROM users without WHERE erases every row in the table. Add LIMIT 1 for single-record deletes as an extra guardrail.

  • Ignoring foreign key errors: Attempting to hard-delete a parent user referenced by a restrictive foreign key in invoices throws a PDOException (23000). Decide deliberately between ON 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
PHP Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum