About Me

Friday, 13 April 2012

MySQL Delete

MySQL Delete

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:

<?php
// Connect to MySQL

// Delete Bobby from the "example" MySQL table
mysql_query("DELETE FROM example WHERE age='15'") 
or die(mysql_error());  
?>
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.

0 comments:

Post a Comment