How to delete a row from a database
Short answer
Run DELETE with a condition on the identifier:
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE products (id INTEGER PRIMARY KEY, title TEXT, price INTEGER)');
$pdo->exec("INSERT INTO products (title, price) VALUES ('Tea', 250), ('Coffee', 400), ('Juice', 180), ('Green tea', 300)");
$statement = $pdo->prepare('DELETE FROM products WHERE id = ?');
$statement->execute([2]);
echo $statement->rowCount(), ' ', $pdo->query('SELECT COUNT(*) FROM products')->fetchColumn();Output:
1 3Soft deletion
Often a record is not erased but marked as deleted — it can be restored. A deleted_at column is added, and marked rows are excluded with WHERE deleted_at IS NULL.
Functions used in this recipe
- PDO — A database connection.
- PDOStatement — A prepared statement and its result.
- count — Returns the number of elements in an array.