MySQLi – Delete data

As the title suggests, we will learn how to delete a single or multiple rows (records) from a table within our database.

I will no longer be including the connection code in the examples. You should realise that you must connect to the database in every new PHP script.

1
2
3
4
5
6
7
8
9
 
$sql = "DELETE FROM Messages 
WHERE email = 'smith@smith.com'";
 
if ($conn->query($sql) === TRUE) {
    echo "Message has been deleted";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

The above script will delete the message stored in the table that has the email ‘smith@smith.com’ associated with it. Please note that if there is more than one record associated with the email address ‘smith@smith.com’ then they will all be deleted. Best using a unique identifier.

You can delete everything from the table by using the following code:

1
2
3
4
5
6
7
8
 
$sql = "DELETE * FROM Messages";
 
if ($conn->query($sql) === TRUE) {
    echo "All messages have been deleted";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

The ‘*’ denotes everything and can also be used to SELECT everything from the table.