How to delete record in database

One of the database manipulation language is the delete SQL statement. Sometimes it is necessary to have a database function to delete records but deleting records to database is not advisable instead to archive it only. The example code below is PHP code that demonstrate on how to delete records that is stored in the MySQL database. The PHP code will first connect to the host computer using the database user name and password, then retrieve the records stored in the database table, display the records to the browser so that user can choose which record to be deleted and create a PHP code that will delete the selected record to the MySQL database.

To support the above statement let assume that the name of database is “mydatabase”, the name of table is “ Persons” with the following fields: personID, FirstName, LastName, and Age. The PHP code below will serve as reference or example to those who want and learn database web programming.

PHP code:
File Name: view_delete.php

<html>
<form action = "delete.php" method="get">
Enter Person ID: <input type="text" name="id" />
<input type="submit" value="Delete"/>
</form>
</html>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("mydatabase", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1' width='32%'>
<tr>
<th>Person ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['personID'] . "</td>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age']. " </td>";
  echo "</tr>";
  }
echo "</table>";
mysql_close($con);
?>

PHP code:
File Name: delete.php

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("mydatabase", $con);
$personID=$_GET['id'];
$sql="delete from Persons where personID = $personID";
mysql_query($sql);
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record deleted!";
mysql_close($con);
?>

In the above example we need two PHP file in order to delete record that is stored in the MySQL database. The first file is the PHP code that will retrieve data to database and display to user so that they can choose which record to be deleted. The second PHP file is the PHP code the will delete the selected record to the database table.