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
Release: 2024-12-12 18:24:14
Original
897 people have browsed it

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;
Copy after login

Object-oriented:

$from = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $from->diff($to)->y;
Copy after login

In MySQL, you can use the following query to calculate age:

SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template