Forum Moderators: coopster

Message Too Old, No Replies

PHP vs Mysql in age calc

Which is best, fastest, etc..

         

HeadBut

11:26 pm on Jul 14, 2005 (gmt 0)

10+ Year Member



Which of these should I use, or do you have a better soultion:

SELECT `ID` , UNIX_TIMESTAMP(CreationDate) AS CreationDate, `AccountType` , `username` , DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(age, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(age, '00-%m-%d')) AS age, `age` as DOB
FROM tablea
WHERE ID = '".$_SESSION['ID']."
LIMIT 1'"

or should I do it with php:

function calc_age($DOB) {
    $age = (date("Y") - date("Y",$DOB));
    if (mktime(0,0,0,date("m",$DOB),date("j",$DOB),date("Y")) <= time())
        return $age;
    else
        return $age -1;
}

thanks

coopster

11:59 pm on Jul 14, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You would have to time it to be sure, but I think you'll find the database more efficient. However, you can speed up that query by using a bit of logic, especially if your birth date is stored and formatted in ISO format.
SELECT 
ID,
UNIX_TIMESTAMP(CreationDate) AS CreationDate,
AccountType,
username,
(YEAR(NOW()) - YEAR(birthdate)) - (RIGHT(NOW(),5) < RIGHT(birthdate,5)) AS age
FROM tablea
WHERE ID = '".$_SESSION['ID']."'
LIMIT 1
;

[dev.mysql.com...]

HeadBut

12:03 am on Jul 15, 2005 (gmt 0)

10+ Year Member



ok, so how can I do it with the age field set to 0000-00-00 00:00:00 datetime format?

coopster

12:33 am on Jul 15, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



If your MySQL version is >= 4.1.1 you could extract just the date portion with the DATE function.
SELECT  
ID,
UNIX_TIMESTAMP(CreationDate) AS CreationDate,
AccountType,
username,
(YEAR(NOW()) - YEAR(birthdate)) - (RIGHT(NOW(),5) < RIGHT(DATE(birthdate),5)) AS age
FROM tablea
WHERE ID = '".$_SESSION['ID']."'
LIMIT 1
;