KennethC
KennethC

Reputation: 756

PHP - subtracting today's year with an integer or string

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

Upvotes: 1

Views: 242

Answers (2)

Dimak
Dimak

Reputation: 13

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;
}

Upvotes: 0

Niki van Stein
Niki van Stein

Reputation: 10734

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).

Upvotes: 2

Related Questions