-1

I have made a script that displays persons who are having their birthday today. Beside this, I would like to show the age of those persons. I have found many workable solutions, but I don't know how to implement in my current code.

Here's my current code:

<?php
$sql = "SELECT * FROM birthday WHERE MONTH(dob) = MONTH(NOW()) AND DAY(dob) = DAY(NOW())";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
echo "<p>".$row["first_name"]." ".$row["last_name"]."</p>";
}
}
else
{
echo "There are no birthdays today";
}
$conn->close();
O. Jones
  • 103,626
  • 17
  • 118
  • 172

1 Answers1

0

Edit: This is of course only correct at and after the day of your birthday. But since you are displaying the age only at the day of the birthday this equation is correct in your case.

Isn't the age simply the current year minus the year of the birth? So you can change your select to:

SELECT *, YEAR(NOW()) - YEAR(dob) AS age FROM birthday WHERE MONTH(dob) = MONTH(NOW()) AND DAY(dob) = DAY(NOW())

or you can do it the php way:

$sql = "SELECT * FROM birthday WHERE MONTH(dob) = MONTH(NOW()) AND DAY(dob) = DAY(NOW())";
$result = $conn->query($sql);
$current_year = date("Y");
if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
        $birthday = date_parse($row["dob"]);
        $age = null;
        if(is_array($birthday)){
            $age = $current_year - $birthday["year"];
        }
        echo "<p>".$row["first_name"]." ".$row["last_name"]." is now " + $age + " years old.</p>";
    }
}
else{
    echo "There are no birthdays today";
}
$conn->close();
miile7
  • 2,547
  • 3
  • 23
  • 38
  • That's the definition of the age, isn't it? https://en.wiktionary.org/wiki/age#Synonyms "[P]eriod (in years[...]) something has been alive". That is the year of the birth minus the current year. Example: You are born in 1980, 2020 - 1980 = 40. That's your age (at and after the day of your birthday). – miile7 May 21 '20 at 11:08
  • No. The question is about "displaying the age **at the day of the birthday**". That's why one can ignore the days. The age is only shown and caluclated in December 2020, on your birthay. – miile7 May 21 '20 at 11:11