1

I have a form that requires users to enter their birthdate in the form of YYYY/MM/DD.

That form submits their birthday to database="members_info" table="members" and the slot is called "dob".

The information shows up as "YYYY-MM-DD". I am trying to somehow push this information through a code that changes their birthday to an age, based on today's time, and echoes that date onto the page.

My code follows:

<?php
//connect to database
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "member_info";
$db_table = "members";

@mysql_connect("$db_host","$db_username","$db_pass") or die ("Could Not Connect to Database");
@mysql_select_db("$db_name") or die ("No such database exists");

//querying database
$sql = mysql_query("SELECT * FROM members WHERE id = '1' ");

//fetch results
while ($rows = mysql_fetch_array($sql)) { 
$age = $rows['dob'];
}

//subtract birthdate from birthdate to get age
$from = new DateTime($age);
$to = date("y/m/d");

echo $from->diff($to)->y
?>

I've tried numerous other options and they don't work, I think this is the closest I've gotten. What is wrong with my code?

Also, when I test to see if the date function "date("y/m/d");" works, it works but the day shows a day ahead of today's date. I'm lost in this seemingly impossible task.

Pang
  • 9,564
  • 146
  • 81
  • 122

1 Answers1

1

You can do it straight in MySQL:

SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age FROM members WHERE id = '1' 

Than you are to access to age as the new field created in MySQL:

$sql = mysql_query("SELECT YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age FROM members WHERE id = '1' ");

while ($rows = mysql_fetch_array($sql)) { 
    $age = $rows['age'];
}

echo $age;
Mr.Web
  • 6,992
  • 8
  • 51
  • 86