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

Susan Sarandon
Release: 2024-10-24 09:06:29
Original
143 people have browsed it

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

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

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

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!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!