Home >Database >Mysql Tutorial >How to Calculate Age from Date of Birth Using PHP and MySQL?

How to Calculate Age from Date of Birth Using PHP and MySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 18:24:14906browse

How to Calculate Age from Date of Birth Using PHP and MySQL?

How to Calculate Age from Date of Birth in PHP and MySQL

To convert a date of birth to age in PHP, you can utilize the following PHP functions:

PHP (procedural and object-oriented)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn