To remove records from a MySQL table, you use the DELETE FROM SQL statement. Like the update command, deleting is a powerful action that must be used carefully to avoid accidental data loss.
The DELETE FROM statement specifies the table and a WHERE clause to identify which record(s) to remove.
DELETE FROM Users
WHERE id = 3;
WHERE clause, ALL records in the table will be deleted. This action is usually irreversible!
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL to delete a record
$sql = "DELETE FROM Users WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "DELETE FROM Users WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM Users WHERE id=3";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Just like with updates, you can check how many rows were actually removed:
$conn->affected_rows;mysqli_affected_rows($conn);$stmt->rowCount(); (if using a prepared statement).delete.php?id=3), to prevent SQL injection.TRUNCATE TABLE table_name;. This is faster than DELETE but cannot be rolled back in some systems.