Tutorial :How to get the age from a birthdate using PHP & MySQL?



Question:

I ask my users for their birthdate and store it in my database in the following way $month $day $year output May 6 1901 but I was wondering how can I get the age from the stored birthdate using PHP & MySQL?

Here is the PHP code.

if (isset($_POST['submitted'])) {    $mysqli = mysqli_connect("localhost", "root", "", "sitename");  $dbc = mysqli_query($mysqli,"SELECT users.*                               FROM users                                WHERE user_id=3");    $month_options = array("Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");    $day_options = array("Day", "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");    $month = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['month'])));  $day = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['day'])));  $year = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['year'])));          if (mysqli_num_rows($dbc) == 0) {              $mysqli = mysqli_connect("localhost", "root", "", "sitename");              $dbc = mysqli_query($mysqli,"INSERT INTO users (user_id, month, day, year)                                            VALUES ('$user_id', '$month', '$day', '$year')");      }          if ($dbc == TRUE) {              $dbc = mysqli_query($mysqli,"UPDATE users                                            SET month = '$month', day = '$day', year = '$year'                                           WHERE user_id = '$user_id'");                echo '<p class="changes-saved">Your changes have been saved!</p>';        }          if (!$dbc) {              print mysqli_error($mysqli);              return;      }  }  

Here is the html.

<form method="post" action="index.php">      <fieldset>          <ul>              <li><label>Date of Birth: </label>              <label for="month" class="hide">Month: </label>              <?php // month options                echo '<select name="month" id="month">' . "\n";                foreach($month_options as $option) {                  if ($option == $month) {                    echo '<option value="' . stripslashes(htmlentities(strip_tags($option))) . '" selected="selected">' . stripslashes(htmlentities(strip_tags($option))) . '</option>' . "\n";                  } else {                    echo '<option value="'. stripslashes(htmlentities(strip_tags($option))) . '">' . stripslashes(htmlentities(strip_tags($option))) . '</option>'."\n";                  }                }              echo '</select>';                ?>              <label for="day" class="hide">Day: </label>              <?php // day options                echo '<select id="day" name="day">' . "\n";                foreach($day_options as $option) {                  if ($option == $day) {                    echo '<option value="' . stripslashes(htmlentities(strip_tags($option))) . '" selected="selected">' . stripslashes(htmlentities(strip_tags($option))) . '</option>' . "\n";                  } else {                    echo '<option value="'. stripslashes(htmlentities(strip_tags($option))) . '">' . stripslashes(htmlentities(strip_tags($option))) . '</option>'."\n";                  }                }              echo '</select>';                ?>                            <label for="year" class="hide">Year: </label><input type="text" name="year" id="year" size="4" maxlength="4" value="<?php if (isset($_POST['year'])) { echo  stripslashes(htmlentities(strip_tags($_POST['year']))); } else if(!empty($year)) { echo  stripslashes(htmlentities(strip_tags($year))); } ?>" /></li>                  <li><input type="submit" name="submit" value="Save Changes" class="save-button" />                  <input type="hidden" name="submitted" value="true" />              <input type="submit" name="submit" value="Preview Changes" class="preview-changes-button" /></li>              </ul>      </fieldset>    </form>  


Solution:1

If you just need to calculate age from a given date, there are lots of answers to this that have already been posted. See this one: Calculate years from date


Solution:2

With datetime:createfromformat you could parse the date into a DateTime object and do you calculations on the object which makes it quite easy. Requires php 5.3 though.


Solution:3

function getAge($then) {      $then = date('Ymd', strtotime($then));      $diff = date('Ymd') - $then;      return substr($diff, 0, -4);  }  

From JYelton's answer, just put this function in your code, and send your date to it:

$age = getAge('June 30 1959');    echo $age;  


Solution:4

Try this:

$age = floor((time() - mktime(0,0,0,$month,$day,$year))/31536000);  

It takes the time now, subtracts the time of their birth, converts it to years and floors it giving you their current age.


Solution:5

you can try this ::

if( isset($_POST['submit']) )     {     $day = $_POST['day'];     $month = $_POST['month'];     $year = $_POST['year'];       $cal_date = mktime(0, 0, 0, $month, $day, $year );  // convert in second     $start_date = date('Y-m-d',$cal_date);   // make real time as  Year-month-day for store value in database       $birthDay = strtotime("now") - strtotime($start_date);       echo substr($birthDay, 0, -4);        }  


Solution:6

Create function in php :

function calculateage($BirthDate)  {  list($Day, $Month, $Year) = explode(".", $BirthDate);    $YearDiff = date("Y") - $Year;    if(date("m") < $Month || (date("m") == $Month && date("d") < $DayDiff))  {  $YearDiff--;  }  return $YearDiff;  }  

call function where age shown like

calculateage($date)  

Where $date is birthdate in mysql table


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »