1

I am creating a online record for our family members.

I have two tables Member and MemberDetails, and the BirthDate is inserted in the 'member' table. I want to calculate age using this BirthDate stored in table 'Member' and store it in table MemberDetails for each member under the column 'Age'.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Try this [link](http://stackoverflow.com/questions/7749639/how-to-get-the-difference-in-years-from-two-different-dates). In this example your date2 will be current date. – Think Different Apr 02 '14 at 09:11
  • There's usually no point in taking a stored date of birth and converting it to an age to store, as it provides a way for discrepancy to leak into the database (and ages need to be recalculated anyway). Why not calculate the age in real-time when you need it? – halfer Apr 02 '14 at 10:05
  • Thanks halfer, but i need the age calculated to sort the members into different age groups. :-) – user3488543 Apr 02 '14 at 12:25

3 Answers3

2

You can do this directly in SQL,

Try something like

INSERT INTO Member_Detail (id, dob)
VALUES SELECT id, TIMESTAMPDIFF(YEAR, dob, CURDATE()) FROM Member
Kami
  • 19,134
  • 4
  • 51
  • 63
  • This will update all members. This should run done daily (to ensure current ages), as well as whenever a member is added. Ideally this would use a date of death in place of current date if not null. – Paul Gregory Apr 02 '14 at 09:49
  • Thank you Kami , seems like this will solve my query. – user3488543 Apr 02 '14 at 12:25
  • Paul, Thank you for the advice, i am planning on running the query via phpmyadmin once and then write a query in the insert member page. – user3488543 Apr 02 '14 at 12:27
0

Try this -

<?php
$birthDate = "05-03-1991";  // m-d-Y
$birthDate = explode("-", $birthDate);

$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));

echo "Your age is:" . $age;
Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
0

Example:-

<?php
  //date in mm/dd/yyyy format; or it can be in other formats as well
  $birthDate = "12/17/1983";
  //explode the date to get month, day and year
  $birthDate = explode("/", $birthDate);
  //get age from date or birthdate
  $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
    ? ((date("Y") - $birthDate[2]) - 1)
    : (date("Y") - $birthDate[2]));
  echo "Age is:" . $age;
?>

or refer this link PHP calculate age

Community
  • 1
  • 1
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62