The DELETE statement is used to delete records from a database table.
-
Syntax:
DELETE FROM table_name WHERE condition
The
WHERE condition clause is very important, it specifies which row or rows that should be deleted. It's important becouse once you have deleted a record, there is no way of retrieving it, unless you backed up the database beforehand.
If you leave WHERE out, MySQL will delete every record in a table, making it empty again.
The DELETE statement is sent to the MySQL server with the
query() method of the mysqli object.
-
Example
In the previous lessons was created a table named "users" and we added some data in it. Here is how it looks the first three records.
id | name | password | email | reg_date |
1 | Marius | faith | name@domain.net | 2011-03-24 09:51:46 |
2 | MarPlo | peace | new_mail@domain.com | 2011-03-27 10:20:58 |
3 | I_AM | love | address@domain.net | 2011-03-24 10:10:27 |
In this example, we'll delete all the records in the "users" table where name='MarPlo':
<?php
// connect to the "tests" database
$conn = new mysqli('localhost', 'root', 'pass', 'tests');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// DELETE sql query
$sql = "DELETE FROM `users` WHERE `name`='MarPlo'";
// perform the query and check for errors
if (!$conn->query($sql)) {
echo 'Error: '. $conn->error;
}
$conn->close();
?>
- This code we'll delete all the rows from the "users" table where name='MarPlo', so, if there are more users (records) with the name MarPlo in this table, MySQL will delete all of them.
To be shure which record will be deleted, you can add another condition in the WHERE clause (with the AND operator), that specifies more exactly which row to be removed, also, you can apply the LIMIT option to set how many rows to be deleted.
Example:
$sql = "DELETE FROM `users` WHERE `name`='MarPlo' AND `id`=2 LIMIT 1";
After the deletion, the first three rows in "users" table will look like this:
id | name | password | email | reg_date |
1 | Marius | faith | name@domain.net | 2011-03-24 09:51:46 |
3 | I_AM | love | address@domain.net | 2011-03-24 10:10:27 |
4 | PloMar | love_light | a_name@domain.net | 2011-03-24 14:39:49 |
- As you can see, the row with name='MarPlo' (id=2) was deleted.
- If you perform an delete query that doesn't actually remove any record (
becouse the WHERE condition doesn't match any row), you won't see any errors but no rows will be affected.
• To delete the table itself, use DROP TABLE:
DROP TABLE tablename
• To delete an entire database, including every table therein and all of its data, use DROP DATABASE:
DROP DATABASE database_name