PHP MySQL
Create & Test MySQL Database

Delete a Record

The process of deleting a record makes use once again of the mysql_query function.

It uses the SELECT method with the WHERE definition.

Note: If you have accessed this web page via a search engine, you should go back and start at the Beginning.
This tutorial is designed to be viewed and executed in sequence.
Learn to build your database right on your PC and Export it to your website.

 

The query form used to access this script would be similar to the one used for editing a record. A list of existing data would be displayed and below it a form to choose a line for removal. The script is identical to the update form but calls the script birthdays_delete_record.php.

Copy & Save as: birthdays_delete_form.php

<html><head><title>Birthdays Update Form</title>
</head>
<body>
<?
/* Change next two lines if using online */
$db="newdb";
$link = mysql_connect('localhost', '', '');
if (! $link)
die(mysql_error());
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
$result = mysql_query( "SELECT * FROM birthdays" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
print "There are $num_rows records.<P>";
print "<table width=600 border=1>\n";
while ($get_info = mysql_fetch_row($result)){
print "<tr>\n";
foreach ($get_info as $field)
print "\t<td>$field</td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close($link);
?>
<br>
<form method="POST" action="birthdays_delet_record.php">
<pre>
Enter Id Number to Edit: <input type="text" name="id" size="5">
<input type="submit" value="Submit"><input type="reset">
</pre>
</form>
</body>
</html>

Copy & Save as: birthdays_delete_record.php

<?
$id=$_POST['id'];
$db="newdb";
$link = mysql_connect("localhost", "root", "");
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
mysql_query("DELETE FROM birthdays WHERE id=$id");
mysql_close($link);
?>

One fallacy of this simple script is that it will remove the id field as part of the record. That means that if you have 10 records and delete the record with id number 5, your existing id fields will be 1 to 4 and 6 to 10. The next time you add a record it will be added as 11 in the 5 spot.

MySQL Tutorial

To extend your knowledge of MySQL study the Docs and Tutorials at the official MySQL website. MYSQL.com