Formatting Input and Output

Another area to be cautious about is how data are displayed. Sometimes the way the data comes back from the database is not very readable or useful to the viewer, so it has to be formatted. PHP functions can be used for this as well. For example, here is a raw date value that came from SQL Server:

1943-05-29 00:00:00.000

format_date is a function that can format a SQL Server date to mm/dd/yyyy format:

function format_date($str)
{
  return substr($str, 5, 2) . "/" . substr($str,8,2) . "/" . substr($str, 0,4);
}

Here is how it might be used:

<?php
  function format_date($str)
  {
    return substr($str, 5, 2) . "/" . substr($str,8,2) . "/" . substr($str, 0,4);
  }

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

  $emp_id = $_POST["id"];

  $stmt = "Select * from tblEmployees where EmployeeNumber = $emp_id";

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

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

  $lastname = odbc_result($result, "lastname");
  $firstname = odbc_result($result, "firstname");
  $birthdate = format_date(odbc_result($result, "birthdate"));
  $isadmin = odbc_result($result, "isadmin"); // stored as 0=no, 1=yes
  $yes_status = "";
  $no_status = "";

  if ($isadmin == 0) $no_status = "checked";
  if ($isadmin == 1) $yes_status = "checked";

  odbc_free_result($result);

  odbc_close($db);
?>
<form method="post" action="edit_employee.php">
  Last Name: <input type="text" name="lastname" value="<?php echo $lastname;?>">
  First Name: <input type="text" name="firstname" value="<?php echo $firstname;?>">
  Birth Date: <input type="text" name="birthdate" value="<?php echo $birthdate;?>">
  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

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

But what about when a date is entered? How do you make it easier for the user to enter a date? Luckily, PHP has some powerful date input functions that will probably work well enough for your needs, and SQL Server is fairly tolerant as well -- though we'll force yyyymmdd format.

$bd = $_POST["birthdate"];

$bdate = date("Ymd", strtotime($bd));

$upd_stmt = "update tblEmployees set birthdate='$bdate' where employeenumber=$id";