Editing Employee Information

A file named edit_one_emp.php displays the input fields of the existing record using an HTML form. When the user clicks on Submit, the form is submitted to the edit_emp.php script, which will take that information and update the corresponding database record.

edit_one_emp.php is an HTML form filled in by the data from the employee. The id of the employee is built into the link in showEditableEmps.php and passed as a query string to edit_one_emp.php. However, when edit_emp.php gets sent the input, the id is not passed on (no query), so a special "hidden" <input> variable is required to hold the employee number.

<?php
  // Connect to the database and get the data of interest

  $db = odbc_connect("iaidb", "css_test", "password") or die ("could not connect<br />");

  $id = $_GET["id"];

  $stmt = "Select LastName, FirstName, BirthDate, IsAdmin from tblEmployees where employeenumber=$id";

  $result = odbc_exec($db, $stmt);

  if ($result == FALSE) die ("could not execute statement $stmt<br />");

  $ln = odbc_result($result, "lastname");
  $fn = odbc_result($result, "firstname");
  $bd = odbc_result($result, "birthdate");
  $ad = odbc_result($result, "isadmin");
  $yes_status = "";
  $no_status = "";
  if ($ad == 1) $yes_status = "checked";
  if ($ad == 0) $no_status = "checked";
?>

<form method="post" action="edit_emp.php">
  <input type="hidden" name="id" value="<?php echo $id;?>">
  <ul>
    <li>Last Name: <input type="text" name="lastname" value="<?php echo $ln;?>">
    <li>First Name: <input type="text" name="firstname" value="<?php echo $fn;?>">
    <li>Birth Date: <input type="text" name="birthdate" value="<?php echo $bd;?>">
    <li>Admin: <input type="radio" name="isadmin" value="yes" <?php echo $yes_status;?>>Yes
               <input type="radio" name="isadmin" value="no" <?php echo $no_status;?>>No
  </ul>

  <input type="submit" value="Submit">
</form>

Updating the employee information uses edit_emp.php to process the input and change the employee information in the table:

<?php
  function dquote($str){
         return str_replace("'","''",$str);
  }

  $db = odbc_connect("iaidb", "css_test", "password") or die ("could not connect<br />");

  $id = $_POST["id"]; // Get the hidden variable's value

  $ln = dquote($_POST["lastname"]);
  $fn = dquote($_POST["firstname"]);
  $bd = date("Ymd", strtotime($_POST["birthdate"]));
  $adm = $_POST["isadmin"]; // either "yes" or "no"
  $ad = 0;
  if ($adm == "yes") $ad = 1;

  $update_stmt =  "update tblEmployees set LastName='$ln', FirstName = '$fn', BirthDate = '$bd', IsAdmin=$ad ".
                          "where EmployeeNumber=$id";

  $result = odbc_exec($db, $update_stmt);

  if ($result == FALSE) die("<br />Could not execute statement ".$update_stmt);

  odbc_free_result($result);
  odbc_close($db);

  include 'showEditableEmps.php';
?>