Maintenance is a very common task that is necessary for keeping MySQL tables current. From time to time, you may even need to delete items from your database.
Some potential reasons for deleting a record from MySQL include when: someone deletes a post from a forum,
an employee leaves a company, or you're trying to destroy your records before the federalies come!
MySQL DELETE Example
The DELETE query is very similar to the UPDATE Query
in the previous lesson. We need to choose a table, tell MySQL to perform the deletion, and provide the requirements that a record must have for it to be deleted.
Say we want to delete the youngest employee from our previously created table because he has to go back to school. This is how we do it.
PHP & MySQL Code:
// Connect to MySQL
// Delete Bobby from the "example" MySQL table
mysql_query("DELETE FROM example WHERE age='15'")
It is important to note that this query would have deleted ALL
records that had an age of 15. Since Bobby was the only
15 year old this was not a problem.
MySQL DELETE Tips
Before performing a large delete on a database, be sure to back up the table/database
in case your script takes off a little more than desired. Test your delete queries
before even thinking about using them on your table. As long as you take caution
when using this powerful query you should not run into any problems.
Download Tizag.com's MySQL Book
If you would rather download the PDF of this tutorial, check out our
MySQL eBook from the Tizag.com store.
You may also be interested in getting the PHP eBook
Found Something Wrong in this Lesson?
Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!