How should PHP code be structured to ensure accurate and reliable results when determining age groups based on date ranges in a database query?

When determining age groups based on date ranges in a database query, it is important to consider the current date and accurately calculate the age of individuals based on their birthdate. To ensure accurate and reliable results, the PHP code should calculate the age dynamically by comparing the birthdate with the current date, rather than relying on static age ranges.

// Assuming $birthdate is the birthdate retrieved from the database
$birthdate = '1990-05-15';
$currentDate = date('Y-m-d');
$age = date_diff(date_create($birthdate), date_create($currentDate))->y;

// Determine age group based on calculated age
if ($age < 18) {
    $ageGroup = 'Under 18';
} elseif ($age >= 18 && $age < 30) {
    $ageGroup = '18-29';
} elseif ($age >= 30 && $age < 50) {
    $ageGroup = '30-49';
} else {
    $ageGroup = '50 and over';
}

echo "Age: $age, Age Group: $ageGroup";