I’m building a form that filters through users based on the selected age range. My database stores users’ birthday in the form year-month-day (ex. 1986-04-23). I’m having trouble writing a function that takes the age subtracts the years from today’s date and converts it back to a date that I can use to compare with those in my database.
So for example if I pass the function “18” it should return “1993-04-15” based on today’s date.
I’m trying to use the strtotime function to accomplish this but can’t seem to get it to work properly. I’ve checked out the PHP manual and read about this function with no avail.
Why not convert to a date first and then subtract the number of years. Just subtracting the age from the year portion could result in an invalid date where the 29th February is involved.
I would think that if you are trying to find user(s) w/in a certain age range, that you would use a todays date type function and subtract that from user inputed information to obtain your range of user(s).
I think you are doing it wrong. You should just ask user to enter date of birth instead of their age. You can always calculate age based on date of birth but you can’t get date of birth based on age.
Here is a simple function to get age based on date of birth:
Users already entered their date of birth when they registered and their DOB is stored in the database. What I was trying to accomplish was a search filter where a user can find other users within a certain age range. The filter would take that age range and search the database for users with a DOB that matches the specified range.
untested, and I am unsure as to whether DATE_ADD is a mysql specific function - there will likely be other ways of doing this, ask on the sql forums on this site.
$age1 = 18;
$age2 = 30+1; // Have to add 1 to the second number or it will end with people who just turned 30!
$sql = "SELECT name
FROM users
WHERE dob
BETWEEN DATE_ADD(CURDATE(), INTERVAL -{$age1} YEAR)
AND DATE_ADD(CURDATE(), INTERVAL -{$age2} YEAR)";