Home  >  Article  >  Backend Development  >  How do I Calculate Age from Date of Birth in PHP and MySQL?

How do I Calculate Age from Date of Birth in PHP and MySQL?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 09:06:29144browse

How do I Calculate Age from Date of Birth in PHP and MySQL?

Determining Age from Date of Birth: PHP and MySQL Solutions

Introduction

Determining the age of a user based on their date of birth is a common task in database management. In this article, we will explore two methods to achieve this task using PHP and MySQL.

PHP Method

Using PHP, we can calculate the age difference between two dates using the DateTime class. Here's an example code snippet:

<code class="php"><?php
$birthdate = new DateTime('1999-03-15');
$today = new DateTime();
$age = $birthdate->diff($today)->y;
echo "Age: $age years";
?></code>

MySQL Method

MySQL provides the TIMESTAMPDIFF() function to calculate the difference between two timestamps. The following query calculates the age difference between the date of birth (date) and the current date:

<code class="sql">SELECT TIMESTAMPDIFF(YEAR, `date`, CURDATE()) AS `age`
FROM users</code>

Specific Example

In your specific example, the following code snippet can be used to calculate the age of a user based on their date of birth:

<code class="php"><?php
if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $dnn = mysql_fetch_array($dn);
    $age = TIMESTAMPDIFF(YEAR, $dnn['date'], CURDATE());
    echo "Age: $age years";
}
?></code>

The above is the detailed content of How do I Calculate Age from Date of Birth in 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