Home > Database > Mysql Tutorial > How Can I Calculate a Person\'s Age from Their Date of Birth Using PHP and MySQL?

How Can I Calculate a Person\'s Age from Their Date of Birth Using PHP and MySQL?

DDD
Release: 2024-11-25 10:25:11
Original
631 people have browsed it

How Can I Calculate a Person's Age from Their Date of Birth Using PHP and MySQL?

Calculating Age Based on Date of Birth

In a database with user information, it's common to have their birthdates recorded. To enhance the functionality, you may need to convert these birthdates into their corresponding ages (in years).

PHP Solution (>=5.3.0)

Object Oriented:

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

Procedural:

echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
Copy after login

MySQL Solution (>=5.0.0)

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

Implementation in PHP:

$dnn = mysql_fetch_array($dn);
$birthDate = $dnn['date'];  // Fetch the birth date from the database

// Calculate age using the object oriented approach (assuming PHP version is >= 5.3.0)
$from = new DateTime($birthDate);
$to   = new DateTime('today');
$age = $from->diff($to)->y;

echo "{$age}";  // Output the calculated age
Copy after login

The above is the detailed content of How Can I Calculate a Person\'s Age from Their 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template