How can variables for day, month, and year be passed into a function for age calculation in PHP when retrieving birthdate data from a MySQL database?
To calculate age from a birthdate retrieved from a MySQL database in PHP, you can pass the day, month, and year as variables into a function that calculates the age based on the current date. You can use the DateTime class to create date objects for the birthdate and current date, calculate the difference in years, and return the age.
function calculateAge($birth_day, $birth_month, $birth_year) {
$current_date = new DateTime();
$birthdate = new DateTime("$birth_year-$birth_month-$birth_day");
$age = $current_date->diff($birthdate)->y;
return $age;
}
// Example of retrieving birthdate data from MySQL database and calculating age
$birth_day = 15;
$birth_month = 6;
$birth_year = 1990;
$age = calculateAge($birth_day, $birth_month, $birth_year);
echo "The person is $age years old.";
Keywords
Related Questions
- What steps can be taken to troubleshoot and resolve discrepancies between query results in PHPMyAdmin and PHP scripts when querying MySQL databases in PHP?
- What steps can be taken to troubleshoot and resolve "illegal character" errors when using iconv function in PHP for encoding conversion?
- Are there any specific differences or nuances in using regular expressions in PHP compared to Perl?