MySQL Delete Data

PHP MySQL Delete Data

You can delete records from an existing MySQL table by using the DELETE FROM statement.


The DELETE Statement

The syntax is straightforward: DELETE FROM table_name WHERE some_column = some_value

CRITICAL WARNING: Notice the WHERE clause in the DELETE statement! The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records in the table will be deleted!

Delete Record Example

<?php
// Database connection code omitted...

// Delete the user who has an ID of 3 $sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); }

mysqli_close($conn); ?>

After running this query, the user with ID 3 will be permanently removed from the database.


Exercise

?

What happens if you run a DELETE statement but forget to include a WHERE clause?