Page 1 of 1
Calculate Age from DOB
Posted: Sun Dec 28, 2003 5:21 am
by stephenp222
Hi,
I have a table which has peoples details in, one field is DOB.
When the persons details are viewed i would like to have their age displayed aswell, this will have to calculated "on the fly" as i don't want to store it in the table.
My date format is "16-Dec-2003" and its not a date field in mysql, just a standard text.
Is this someting that PHP can do?
Can anyone help me out?
Thanks
Stephen
Posted: Sun Dec 28, 2003 5:28 am
by Nay
Here's a way. Extract the text from mysql then use
explode(). Then minus the year from the current year and wala, you've got your age

.
-Nay
Posted: Sun Dec 28, 2003 5:43 am
by stephenp222
ok that sounds easy enough, but, i am very new to PHP and have no idea
on how to start that.
stephen
Posted: Sun Dec 28, 2003 8:57 am
by volka
Why isn't it a date-field when there's a date in?
Nevertheless you can use mysql's date/time functions as long as mysql can cast it to a date/time value. And it has a function
DATEDIFF(expr,expr2) that returns the difference between two dates in days, e.g.
SELECT DATEDIFF(dob, Now()) FROM myTable WHERE id=5
Posted: Sun Dec 28, 2003 9:32 am
by stephenp222
ok,
i have tried this, i get the details displayed correctly, but the age is not entered.
My code is
<?php
$sqlwrk = 'SELECT DATEDIFF (`dob`, Now()) FROM `details` WHERE dob=<?php echo $x_student_id ?>';
echo $arraywrk["DATEDIFF"];
?>
Where am i going wrong?
Posted: Sun Dec 28, 2003 10:49 am
by volka
you're trying to open another php-block within a php-block
Code: Select all
$sqlwrk = 'SELECT DATEDIFF (`dob`, Now()) FROM `details` WHERE dob=' . $x_student_id;
what's in the field
dob? the "day of birth"-date or the student-id? unlikely that it is both.
After you've figured that out you have to use
mysql_query() to send the statement to the mysql-server and fetch the result with e.g.
mysql_fetch_array()
Posted: Sun Dec 28, 2003 3:30 pm
by m3rajk
i created a function for that... if your dates are stored close enough, you can use it without modification. otherwise, here's something forr you to play with to get that. (this is a simple enough thing that i don't see any point in wasting time tryin to get you there since others have ad there's been no feedback stating how far you've gotten)
Code: Select all
function findAge ($dob){
$year=substr($dob,0,4); $month=substr($dob,5,2); $day=substr($dob,8,2); # get year, month, day from dob
$today = localtime();
$age = ($today[5]+1900) - $year; // this can be a year to old!
if ($month < ($today[4]+1)) {return $age;}
elseif ($month > ($today[4]+1)) {$age--; return $age;} // over by a year
else{ // it's the month the user was born. we need to check the day
if ($day > $today[3]) {$age--; return $age;} // over by a year
else {return $age;}
}
}