Delete Employee Page

The delete operation is one of the easiest of the other three operations (e.g., insert, update and select) to implement. Yet, it is the most dangerous process with the capability of deleting ALL of the records in the database if not done right. If you are new to database development, it is best to backup the database if you can because the delete process is irreversible.

Unlike the other pages, only code is needed for the Delete Employee page. There is no need to create:

  1. a form and form elements
  2. a recordset

The reasons these elements are not needed is because:

  1. the page is used only to execute a script
  2. a user will never see this page

The code that will be created will perform the following tasks:

ADD DYNAMIC SCRIPTS

Add SQL DELETE Recordset Script

  1. Open the delete_employee.php page that you created earlier.
  2. Write (or copy) the following highlighted code after the <h2> tag. Comments are NOT highlighted because they are optional but are written to explain code.
    WHY: To create a script (not a recordset) to delete a record from the database based on the recordID variable passed from the Detail page.

    <!-- SQL DELETE QUERY -->
    <?php
    // Store a reference of SQL statement in a variable
    $query_rs_deleteEmployee = "DELETE FROM employees WHERE EmployeeID=$_GET[recordID]";
    // Store a reference of the query in this variable from the SQL variable using the mysql_query function.
    $rs_deleteEmployee=mysql_query($query_rs_deleteEmployee);
    ?>

  3. Save the file.

Add Redirect User Script

After page is submitted and data added to the database, a user needs to be REDIRECTED to the home page (index.php). You could also create a separate confirmation page if you wanted or needed to.

  1. Write the following highlighted code within the PHP block code.
    WHY: To redirect the user to another page and then close the connection to the database.

    $query_rs_deleteEmployee="DELETE FROM employees WHERE EmployeeID=$_GET[recordID]";
    // Redirect user to another page
    header("Location: index.php"); // Close connection once query is complete
    mysql_close();

    ?>

    - If PHP detects an error, the redirect code will not be executed.

  2. CHECKPOINT: Save the file and then open the Employee Master Page (index.php) and click on a list item of an employee that you would like to delete. Then, on the Employee Detail page, click on the DELETE EMPLOYEE button of the selected employee. You should be prompted to ensure that you want to delete the current employee. Click the OK button. You should see that the page immediately returned to the Employee Master Page (index.php) and the employee that was deleted is no longer in the list.