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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 14:36:10761browse

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

How to Calculate Age from Date of Birth

In various scenarios, you may encounter the need to determine the age of an individual based on their date of birth. Let's delve into a comprehensive guide to calculate age in PHP and MySQL.

PHP

When working with PHP versions 5.3.0 or later, you can leverage the following approaches:

  • Object-Oriented Approach:
$from = new DateTime('1970-02-01');
$to   = new DateTime('today');
echo $from->diff($to)->y;
  • Procedural Approach:
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;

MySQL

For MySQL versions 5.0.0 or higher, you can utilize the following query:

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

Example

Let's say you have a PHP script that retrieves a user's date of birth from a MySQL database and wants to display their age:

<?php
$result = mysql_query("SELECT date FROM users WHERE>

The above is the detailed content of How to Efficiently 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