Taking Date from the user as input

I was making a website where I had to take the Date of Birth from the user . Initially , I took the whole date as a string and passed it to MYSQL through PHP , but then my friend ( Prateek) told me to have a drop down menu for the day, month and the year so as to make it look cool and more user friendly ..

So , then I started to do it and discovered many functions like checkdate() in the process .

The final result : date2

This code :

  • Displays three drop down menus one each for the day ,month and the year .
  • It checks the date for validity using PHP .
  • It combines all three (day,month and year) into a MYSQL date format so as to send it to the database
  • It will also show by default the option previously selected . eg If there are many fields in your form then the user enters a wrong date ( let it be 29/02/1990) then it will ask you to enter a correct date and also by default select the day as 29 , month as 02 and year as 1990 .

entereddateThis is being done by $_POST variable of PHP

    Here is the code :

    <tr>
    <td height=”28″>Date of Birth</td>
    <td><select name=”Date” size=”1″ >
    <?php

    $i=1;
    while($i<32)
    {

    if($i==$_POST['Day'])
    echo “<option selected value=”.$i.”>”.$i.”</option>”;
    else
    echo “<option value=”.$i.”>”.$i.”</option>”;
    $i++;

    }

    ?>
    </select>
    <select name=”Month” size=”1″>
    <?php

    $i=1;
    while($i<13)
    {

    if($i==$_POST['Month'])
    echo “<option selected value=”.$i.”>”.$i.”</option>”;
    else
    echo “<option value=”.$i.”>”.$i.”</option>”;
    $i++;

    }

    ?>
    </select>
    <select name=”year” size=”1″>
    <?php

    $i=1980;
    while($i<2000)

    {

    if($i==$_POST['year'])
    echo “<option selected value=”.$i.”>”.$i.”</option>”;
    else
    echo “<option value=”.$i.”>”.$i.”</option>”;
    $i++;

    }

    ?>
    </select></td>
    </tr>

    And then you can check the date like this :

    if(!checkdate($_POST['Month'],$_POST['Day'],$_POST['year']))
    {

    $error[]=”Please enter a correct date”;

    }

    Finally , send it to the database :

    $date=$_POST['year'].”-”.$_POST['Month'].”-”.$_POST['Date'];

    Use this date variable to insert into the database .

    PS: If any one has a better way to do it , please leave it as a comment .

    Leave a Reply