简体   繁体   中英

Date of birth to Age range using PHP

I have a table that stores my customers name and date of birth. For example below:

name       DOB          gender      email
Tony       1987-04-20   male        tony@tony.com
Susan      1985-06-13   female      susan@susan.com

On my site I would like to search for users according to their DOB and display as Age range like this (Under 18, 18-25, 26-35, 36-45, 46-55 and Over 55)

For Tony and Susan, they will fall under 26-35 category. On my site, I would like to have a table that displays the name by age range something like below.

Under 18   18-25   26-35   36-45   46-55   Over 55
xxx        xxx     Tony    xxx     xxx     xxx
xxx        xxx     Susan   xxx     xxx     xxx

Using PHP how can I find the age range from DOB ?

Try Below code

        foreach($rows as $row){
            $d1 = new DateTime($row->DOB);
            $d2 = new DateTime(date("Y-m-d"));

            $diff = $d2->diff($d1);

            echo $diff->y;

        }

i have an example so you can get how you can do

step: 1

 SELECT 
   round(DATEDIFF(CURRENT_DATE,t.birthdate)/365) AS ageInYears,
   name 
 FROM member t

get a name and age from table member

step: 2

SELECT
   (`ageInYears` > 40) as `data1`
   ,name 
  FROM  (step: 1) as t

created column 'data1' age is > 40,you create multiple column on age comparation like ( ageInYears < 18) as data1 ,( ageInYears > 18 and ageInYears < 25) as data2

step: 3

SELECT 
     MAX(IF(`data1` = 1,name,null)) '35to40',
     MAX(IF(`data1` = 0,name,null)) '0to35'
     From (step 2) as t group by name

created column 35to40 and 0to35 using if condition to check where 'data1' = 1 and put there name if not 1 than null

final result

 SELECT 
 MAX(IF(`data1` = 1,name,null)) '35to40',
 MAX(IF(`data1` = 0,name,null)) '0to35'
 From (SELECT 
         (`ageInYears` > 40) as `data1`
         ,name 
             from ( SELECT
                round(DATEDIFF(CURRENT_DATE,t.birthdate)/365) AS ageInYears
                ,name 
                    FROM member t) as t) as t group by name

o/p

 35to40     0to35   
NULL    asdasd
dhara   NULL
NULL    g
ravi    NULL
sonam   NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM