Home » Php » php – Adding date of birth to database

php – Adding date of birth to database

Posted by: admin July 12, 2020 Leave a comment


I’m trying to add fields for Day, Month and Year in registration form and add it to user record in database. So I’ve put this is the form:

<div class="form-group"> 
   <div class="form-inline">
      <div class="form-group pull-right">
         <select name="year" id="year" class="form-control">
            <option value="--" selected>Year</option>                       
                for($i=date('Y'); $i>1899; $i--) {
                    $birthdayYear = '';
                    $selected = '';
                    if ($birthdayYear == $i) $selected = ' selected="selected"';
                    print('<option value="'.$i.'"'.$selected.'>'.$i.'</option>'."\n");
      <div class="form-group pull-right">
        <select name="month" id="month" onchange="" class="form-control" size="1">
            <option value="--" selected>Month</option>
            <option value="01">Jan</option>
            <option value="12">Dec</option>
      <div class="form-group pull-right">
        <select name="day" id="day" onchange="" class="form-control" size="1">
        <option value="--" selected>Day</option>
        <option value="01">01</option>
        <option value="31">31</option>

Then in the php part this


    //hash the password
    $hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);

    //create the activasion code
    $activasion = md5(uniqid(rand(),true));
    $dateOfBirth = $_POST['day']."-". $_POST['month']."-".$_POST['year'];

    try {
        $stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active,user_birthday) VALUES (:username, :password, :email, NOW(), :active, :user_birthday)');

            ':username' => $_POST['username'],
            ':password' => $hashedpassword,
            ':email' => $_POST['email'],                
            ':active' => $activasion,
            ':user_birthday' => $dateOfBirth

When I hit register everything is inserted into database but the date is 0000-00-00. It doesn’t matter what I choose in dropdowns.

The field for user_birthday in database is DATE. Why doesn’t save what is selected?

How to&Answers:

Database format for DATE is YYYY-MM-DD and you are trying to insert DD-MM-YYYY,

That is why its not inserting and taking default value: 0000-00-00.


$dateOfBirth = $_POST['day']."-". $_POST['month']."-".$_POST['year'];


$dateOfBirth = $_POST['year']."-". $_POST['month']."-".$_POST['day'];

Another approach:

Use array of $dateOfBirth

$dobArr = array($_POST['year'], $_POST['month'], $_POST['day']);
$dateOfBirth = implode('-', $dobArr);