1

I have the following columns in my table: birth_year, birth_month, birth_day

example data from the table is

birth_year         birth_month        birth_day
1996               April              1

I only need to get the age of a user.

It doesn't need to be accurate. I just need to subtract the year today and his/her birth_year

example:

his birth_year is 1996

and the date today is 2015

if($row = mysqli_fetch_assoc($query_run)
{
       $birth_day = $row['birth_year'];    //data from the database which equals to 1996
       $today = date("Y");                 //year today
       $age = $today - $birth_day;        //age of this user
        echo $age;                        //this should output 19
}

My problem is the $age variable from the above echoes a blank or null value.

here are the sources that might be similar to my question:

source 1 source 2

The difference between my question and those is that I can't follow the format of DateTime because my registration form looks like this.

enter image description here

Community
  • 1
  • 1
KennethC
  • 746
  • 2
  • 10
  • 27
  • You should not store date data in three separate columns in a database. All DBMS have dedicated types for that, like `datetime` or `timestamp`. – Anders Aug 29 '15 at 12:29
  • Instead of `echo`ing your variables, use `var_dump` so you can see it's type. You're probably using arithmetic with a string.. – Joaquín O Aug 29 '15 at 12:35
  • I used die($age) instead of echo, I thought it will give me the same output. – KennethC Aug 29 '15 at 12:40

2 Answers2

2

Try to use

$age = intval( $today ) - intval( $birth_day );

Also check if your mysql query returns what you expect (you did not provide it so it is hard to check).

Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
0

try this with the datetime:

if($row = mysqli_fetch_assoc($query_run){
    $birth_day = $row['birth_year'];
    $bday = new DateTime($birth_day);
    $today = new DateTime(date("Y"));
    $age = $today->diff($bday);
    echo $age->y;
}
Dimak
  • 13
  • 3