Main Page Content
Using PHP for Date Processing in Forms
Rated 3.67 (Ratings: 9) (Add your rating)
Log in to add a comment
(5 comments so far)
Want more?
- More articles in Site Development
- More articles by jacksonyee
- Introduction
- Selecting Dates and Times
- Using The WriteDateSelect() Function
- Retrieving the Submitted Date
- Retaining Previous Values
- Downloading the Code
Introduction
One of the most time-consuming tasks of any web application developer is dealing with forms. Not only must you decide what information to place onto the form and design the HTML for it, but you also must validate the submitted form data and process it. Fortunately, server-side scripting languages such as Perl and PHP have made our lives much easier, as we can use them to handle repetitive tasks rather than placing the work on ourselves. In this article, we'll take a look at a common task for applications such as calendars and appointment books: handling dates and times.
Selecting Dates and Times
The easiest way for a developer to deal with dates and times is to have the user enter them in a text field as a specific format such as "yyyy-mm-dd," and use PHP's strtotime() function on them. As all user interface developers should know though, users have a habit of not doing what you tell them to do. They might enter in an invalid date without realizing it, or they might mix up the syntax and type "mm-dd-yy" as U.S. users are prone to doing. In order to alleviate the possibility of errors, the <select> element can be used to limit input to specific ranges and ensure proper formats.
By replacing a text field such as
Enter Date (ex: 2002-06-07):
with the select fields
Date (Year-Month-Day): 2000 2001 2002 - 1 2 3 4 5 6 7 8 9 10 11 12 - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
You can ensure that the input will be in the correct format and within the range that you specified.
Of course, it can become a real hassle to write out the various <select> and <option> tags every time you want to use a date field in a form, so why not have PHP do it for you? The following function will write out a select date field for you given a prefix for the fields, the method of the form, the beginning year of the range, and the ending year of the range.
function WriteDateSelect($BeginYear = 0,
$EndYear = 0,
$IsPosted = true,
$Prefix = '')
{
if (! $BeginYear)
{
$BeginYear = date('Y');
}
if (! $EndYear)
{
$EndYear = $BeginYear;
}
$Year = $IsPosted
? (int) $_POST[$Prefix . 'Year']
: (int) $_GET[$Prefix . 'Year'];
$Month = $IsPosted
? (int) $_POST[$Prefix . 'Month']
: (int) $_GET[$Prefix . 'Month'];
$Day = $IsPosted
? (int) $_POST[$Prefix . 'Day']
: (int) $_GET[$Prefix . 'Day'];
echo '
';
for ($i = $BeginYear; $i 


