PHP and SQL Server - Deleting Data

The SQL 'delete' statement can be used for removing a record or records, which looks as follows.

DELETE FROM table_name
​WHERE where_condition

The following example deletes a record from the 'person' table, as previously used in the examples for selecting, inserting and updating data, based on the 'id' being equal to '2'.

<?php

   // Connect to the database.
   require_once('database-connect.php');
   
   // Query parameter.
   $id = 2;
 
   try
   {
      
      // Prepare the query.
      $results = $connect->prepare("DELETE FROM person
                                    WHERE id = ?");
                                    
      // Bind the parameter.
      $results->bindParam(1, $id);
      
      // Execute the query.
      $results->execute();
      
   } catch(Exception $e) {
      
      // If query fails, display an error and exit.
      echo "Error deleting person information.";
      exit;
      
   }

   // Display a message saying person deleted successfully.
   echo "Person deleted successfully.";

?>

The contents of the 'person' table now looks like this.

id firstname lastname title dob
1 Bob Smith Mr 1980-01-20
3 Fred Bloggs Mr 1975-05-07
4 Alan White Mr 1989-03-20
5 Fiona Bloggs Mrs 1985-05-19