Deleting Records from MySQL - Beginner

By: N Rohler



You have the records into the database, but what about deleting them? Fortunately, the process is very straightforward.

We’ll delete records based on the ID value
in the querystring. This means that we would go to deleterecord.php?ID=12 to
delete a record with ID value of 12. First, we open up the connection
to the MySQL database, then choose the database:

$connection = mysql_connect("localhost", "myusername", "mypassword");
mysql_select_db("demo_db", $connection);

Now, we need to determine if the ID parameter is set in the querystring. If
it is set, and it’s a number, everything’s OK. Otherwise, we display an error
message.

if (isset($_GET["ID"]) && is_numeric($_GET["ID"])) {
   //INSERT DELETING CODE HERE

} else {
   die("Please provide a numeric ID value in the querystring.");
}


Now we write the MySQL query to delete the record. To do this, we use DELETE
FROM the_table WHERE ID=(the ID querystring value). Finally, we redirect to a
success page. (Insert this code where the //INSERT DELETING CODE HERE comment
is in the above block.)

mysql_query("DELETE FROM the_table WHERE ID=" . $_GET["ID"]);

header("Location: deletesuccess.php");

To test the work, open up deleterecord.php (or whatever name you saved it as)
in a browser, like this: http://localhost/deleterecord.php?ID=1 . If successful,
you will be redirected to the [non existent] deletesuccess.php.

The complete code listing for deleterecord.php:

<?php
$connection = mysql_connect("localhost", "myusername", "mypassword");

mysql_select_db("demo_db", $connection);

if (isset($_GET["ID"]) && is_numeric($_GET["ID"]))
{
   mysql_query("DELETE FROM the_table WHERE ID=" . $_GET["ID"]);

   header("Location: deletesuccess.php");
} else {
   die("Please provide a numeric ID value in the querystring.");
}
?>

While this is a very simple example, it should get you started working with deleting
records.

Until next time, Happy Coding :-)