Home >Database >Mysql Tutorial >How to Calculate Age from Date of Birth Using PHP and MySQL?
To convert a date of birth to age in PHP, you can utilize the following PHP functions:
Procedural:
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
Object-oriented:
$from = new DateTime('1970-02-01'); $to = new DateTime('today'); echo $from->diff($to)->y;
In MySQL, you can use the following query to calculate age:
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
To retrieve a specific user's date of birth and calculate their age, you can combine the above PHP code with the following SQL query:
SELECT username, email, skype, avatar, date, signup_date, gender, TIMESTAMPDIFF(YEAR, '1970-02-01', date) AS age FROM users WHERE id = $id
By replacing $id with the appropriate user ID, you can fetch the user's information and calculate their age.
The above is the detailed content of How to Calculate Age from Date of Birth Using PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!