Jump to content

Problem Calculating Age


Accurax

Recommended Posts

Im trying to pull a date of birth from my database (mysql) and use this to calculate a users age for display on the page.

 

At the moment i'm storing the date of birth of each user in three different INT fields in my table

 

Year - INT - 4

Day - INT - 2

Month - INT - 2

 

here is the code im trying to use to calculate the age:

 

<?php


//*****
$username = $_SESSION['username'];
$query = "SELECT * FROM users WHERE user_name='$username'";
$result = mysql_query($query)
	or die ("could not find name");
$row = mysql_fetch_array($result);
$day = $row['day'];
$month = $row['month'];
$year = $row['year'];

$birthday = $day-$month-$year;


$today = date('d-m-Y');

$a_birthday = explode('-', $birthday);
$a_today = explode('-', $today);

$day_birthday = $a_birthday[0];
$month_birthday = $a_birthday[1];
$year_birthday = $a_birthday[2];
$day_today = $a_today[0];
$month_today = $a_today[1];
$year_today = $a_today[2];

$age = $year_today - $year_birthday;

if (($month_today < $month_birthday) || ($month_today == $month_birthday && $day_today < $day_birthday))
{
$age--;
}
echo $age;
?>

 

Can anyone please make any suggestions as to why this doesnt work?

 

I dont get an error message at all, it just displays the age as around 2007 all the time.

 

All help appreciated on this, thanks

Link to comment
https://forums.phpfreaks.com/topic/40857-problem-calculating-age/
Share on other sites

Can use this

<?php
<?php
function your_age($month, $day, $year){
$cday = date("d");
$cmonth = date("m");
$cyear = date("Y");
$today = gregoriantojd($cmonth, $cday, $cyear);
$birthday = gregoriantojd($month, $day, $year);
$age = $today-$birthday;
$years = floor($age/365.25);
$days = fmod($age,365.25);

return "You are $years years and $days days old";
}
echo your_age("12", "24", "1945")."<br />";
?>

 

Ray

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.