PHP

Using Form Fields for Date Selection

If you want to offer an HTML form to select a date, like many hotel- and flight-booking services offer, you can use the various parameters of date(); loop through all months of the year; and, therefore, create a selection list of days, months, and years.

<select name="month"><?php
  for ($i = 1; $i <= 12; $i++) {
    $monthname = date('F', mktime(12, 0, 0, $i, 1,
       2005));
    echo "<option value=\"$i\">$monthname</option>";
    }
?></select>

The preceding code contains the code for this; see Figure for the result.

Selecting a Date Using an HTML Form

<form method="post" action="<?php echo
   htmlspecialchars($_SERVER['PHP_SELF']); ?>">
  <select name="day"><?php
    for ($i = 1; $i <= 31; $i++) {
      echo "<option value=\"$i\">$i</option>\n";
    }
  ?></select>
  <select name="month"><?php
    for ($i = 1; $i <= 12; $i++) {
      $monthname = date('F', mktime(12, 0, 0, $i, 1,
         2005));
      echo "<option value=\"$i\">$monthname</
        option>";
    }
  ?></select>
  <select name="year"><?php
    for ($i = 2005; $i <= 2010; $i++) {
      echo "<option value=\"$i\">$i</option>";
    }
  ?></select>
</form>

The month names were automatically generated.

You can replace the microtimestamp() function with the following code:

function microtimestamp() {
  return microtime(true);
}

The function microtime() returns a float value of the current microtime, when the parameter true is provided (this was added in PHP 5). However, this is reportedly slower than using gettimeofday(), which just executes the underlying gettimeofday system call.

by BrainBellupdated
Advertisement: