Forum Moderators: coopster

Message Too Old, No Replies

Calculate age

how old are you

         

gonny

10:07 pm on Sep 23, 2007 (gmt 0)

10+ Year Member



Hi all,

I want to display in profiles hold are users:

We have:
$query = $DB->query(" Select id, byear, bmonth, bday from profile order by RAND() limit 1");
while($row = $DB->fetch_row($query)) {
$id = $row['id'];
$year = $row['byear'];
$month = $row['moth'];
$day = $row['bday'];

$old ="Is? old";
}

How I can calculate how old are? $old ="Is $? old"; ?

phranque

8:00 am on Sep 24, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



$query = $DB->query(" Select id, byear, bmonth, bday, YEAR(NOW()) as nyear , MONTH(NOW()) as nmonth , DAYOFMONTH(NOW()) as nday from profile order by RAND() limit 1");
while($row = $DB->fetch_row($query)) {
$id = $row['id'];
$byear = $row['byear'];
$bmonth = $row['bmonth'];
$bday = $row['bday'];
$nyear = $row['nyear'];
$nmonth = $row['nmonth'];
$nday = $row['nday'];

$old = $nyear - $byear;

if($nmonth < $bmonth){
$old = $old-1;
}elseif($nmonth == $bmonth){
if($nday < $bday ){
$old = $old-1;
}
}

Habtom

8:13 am on Sep 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Actually, converting them to timestamp makes more sense to me.

You can put something like the following:

$year = $row['byear'];
$month = $row['moth'];
$day = $row['bday'];

$born_in = mktime(0, 0, 0, $month , $day, $year);
$current_date = mktime(0, 0, 0, date("m") , date("d"), date("Y"));
$age = floor(($current_date - $born_in)/ 31536000);

echo $age;

Habtom

coopster

3:55 pm on Sep 24, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Here is an old thread that shows you a quick and easy way to calculate age in your PHP logic. You can easily adapt the logic to your sql statement though ...

[webmasterworld.com...]

... and you won't have to, here it is on the MySQL manual pages [dev.mysql.com] ...


SELECT name, birth, CURDATE(), 
-> (YEAR(CURDATE())-YEAR(birth))
-> - (RIGHT(CURDATE(),5)<RIGHT(birth,5))
-> AS age
-> FROM pet;

But you have your birthdate separated already, so just remove the date parsing logic and you have your statement (you may have to pad the month/day integer columns in order to get it cast as a string correctly) ...

SELECT (YEAR(CURRENT_DATE) - byear) - (RIGHT(CURRENT_DATE, 5) < CONCAT(LPAD(bmonth,2,0),'-',LPAD(bday,2,0))) AS age FROM profile