-2

In DB I have a field that contains user's birthday. Example: 01.09.1994 I have a PHP function that calculates of user's birth. Now the thing that I want to do: I want to search all the users with age 18 for example, but I want to do this in the sql query. How can this happen?

"SELECT * FROM `users` WHERE `birth` = '18'"

How with sql to automatically turn the birth(01.09.1994) into ages, without getting the results and then turn the birthday in ages with php?

Tab Alleman
  • 31,483
  • 7
  • 36
  • 52

1 Answers1

1

The date you are saving is not a real date and it needs to be converted to real date using str_to_date function and then using the timestampdiff you can get the age as

mysql> select timestampdiff(year,str_to_date('01.06.1993','%d.%m.%Y'),curdate()) as age ;
+------+
| age  |
+------+
|   21 |
+------+

So if the column name is dob in the table and you want to find all the users having age = 18 you can do as

select * from users
where 
timestampdiff(year,str_to_date(dob,'%d.%m.%Y'),curdate()) = 18
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63