Jump to content


Photo

PHP to find age *SOLVED*


  • Please log in to reply
16 replies to this topic

#1 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 06:12 PM

ok, i
$bday_day //birthday day
$bday_month //birthday month
$bday_year //birthday year
$today = getdate();
previously defined from a mysql grab i've done (the birthday stuff is in the database in columns bday_day, bday_month, bday_year)

what i'd like to do is use this data to find out how old the person is and display it


#2 gmwebs

gmwebs
  • Members
  • PipPipPip
  • Advanced Member
  • 174 posts
  • LocationLondon

Posted 13 October 2006 - 06:18 PM

A quick Google search found me this... Should do the trick?

http://www.nbrandt.c...e-from-date.php

HTH

#3 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 06:41 PM

yea, i saw that, but it finds the age if you input a specific date, not exactly what i'm need/wanting.

but i would use a function right?  i know diddly-squat about those.

#4 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 13 October 2006 - 06:47 PM

but i would use a function right?  i know diddly-squat about those.

it's impossible to use PHP without some knowledge of functions. echo itself is a function. mysql_query is a function. the list goes on. i've written a function i often use for this purpose:

<?php
// returns a persons age given their date of birth
function getage($dob)
{
   $exp = explode('-', $dob); // we now have the year[0], month[1] and date[2]
   $current = getdate();

   // get an estimate of years
   $ret = $current['year'] - $exp[0];
   
   if ($ret > 110)
   {
      return 0; // too old - possible no date parameter was specified
   }

   // have we reached their birthday month?
   if ($current['mon'] <= $exp[1])
   {
      $ded = 1; // we arent gonna DEDuct a year yet
      
      // are we in their birthday month?
      if (($current['mon'] == $exp[1]) && ($current['mday'] >= $exp[2])) 
      {
         $ded = 0;
      }

      $ret -= $ded; // deduct a year as this years birthmonth not arrived
   }
   return $ret;
}
?>

all it needs is a date of birth (YYYY-MM-DD format) and it'll return the age. so:

$age = getage('1980-01-16');

echo $age; // 26

"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#5 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 13 October 2006 - 06:55 PM

A person born in 1986 is 20 this year, BUT, if the birthday is later in the year than today, they are still only 19, so, putting this logic into a function

<?php
function getAge ($bday, $bmon, $byr) {
    $ynow = date('Y');
    
    $age = $ynow - $byr;
        // format birth month and day as "0901"
    $bmd = sprintf ('%02d%02d', $bmon, $bday);
        // format today monthand day in same way
    $mdnow = date('md');
    
    if ($bmd > $mdnow) $age -= 1;   // sub 1 from age if not there yet
    
    return $age;
}

// call the function to get the age
$age = getAge ($bday_day, $bday_month, $bday_year);

echo $age;

?>


If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#6 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 07:02 PM

hey, that looks like a winner.  but it leaves me with two new problems


1]  my birthday data is from seperate columns in the database.  how would i merge them to make it the necessary formatting for your code?

2]  my birthday data is of the form YYYY for year, M for month, and D for day, when it needs to be (YYYY-MM-DD). i.e.  the 1st shows as '1' not '01' and August shows as '8' not '08'.  would i use a push to add the preceeding zeros? 

#7 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 13 October 2006 - 07:15 PM

??? ???

1 ) my function passes the date as the 3 separate fields
2 ) it reformats month "1" as "01" and day as "01"
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#8 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 07:24 PM

lol, Barand my response was to the other guy, you posted while i was typing,lol

#9 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 13 October 2006 - 07:37 PM

and to be fair, the function I use is one I wrote ages back and whilst it's worked for me, it's a bit crusty. looking at the one provided by Barand, his is much simpler - I'll probably be switching very soon :)
"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#10 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 07:38 PM

hmm, barand, should i modify the function getAge ($bday, $bmon, $byr) to show bday_day,bday_month,bday_year?  i copied and pasted it straight into place and it gave me an error on that line

#11 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 13 October 2006 - 07:48 PM

The variable names in the function definition are irrelevant, they could be $a, $b, $c.

It depends on what your code is to call the function.


@RedBull,

A problem with passing YYYY-MM-DD then using php datetime functions to convert  is that it doesn't work if the DOB is earlier than 1970 with older version of PHP. Later ones create -ve timestamp values for older dates.

PS a general observation, your explodes the "YYYY-MM-DD" date.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#12 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 07:54 PM

ok, so why do i get the error?

http://www.ice-squad...Memberslist.php <--see here

#13 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,017 posts

Posted 13 October 2006 - 07:57 PM

That error is telling you that the function is defined more than once in your code.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#14 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 08:02 PM

hmm, i don't see where it is...you look...
<?php
//----------------------------
// Require
//----------------------------
require "forums/conf_global.php"; //because this file will not be located in the forums directory.

//-------------------------------
// Connect To MySQL
//-------------------------------
mysql_connect($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass']) or die(mysql_error());
mysql_select_db($INFO['sql_database']) or die(mysql_error());


$define_country = array("u"=>"United States","e"=>"England","c"=>"Canada","m"=>"Mexico","a"=>"Aruba","o"=>"Other");
$define_state = array("AL"=>"Alabama","AK"=>"Alaska","AZ"=>"Arizona","AR"=>"Arkansas","CA"=>"California","CO"=>"Colorado","CT"=>"Connecticut","DE"=>"Delaware","DC"=>"District of Columbia","FL"=>"Florida","GA"=>"Georgia","HI"=>"Hawaii","ID"=>"Idaho","IL"=>"Illinois","IN"=>"Indiana","IA"=>"Iowa","KS"=>"Kansas","KY"=>"Kentucky","LA"=>"Louisiana","ME"=>"Maine","MH"=>"Marshall Islands","MD"=>"Maryland","MA"=>"Massachusetts","MI"=>"Michigan","MN"=>"Minnesota","MS"=>"Mississippi","MO"=>"Missouri","MT"=>"Montana","NE"=>"Nebraska","NV"=>"Nevada","NH"=>"New Hampshire","NJ"=>"New Jersey","NM"=>"New Mexico","NY"=>"New York","NC"=>"North Carolina","ND"=>"North Dakota","MP"=>"Northern Mariana Islands","OH"=>"Ohio","OK"=>"Oklahoma","OR"=>"Oregon","PA"=>"Pennsylvania","PR"=>"Puerto Rico","RI"=>"Rhode Island","SC"=>"South Carolina","SD"=>"South Dakota","TN"=>"Tennessee","TX"=>"Texas","UT"=>"Utah","VT"=>"Vermont","VI"=>"Virgin Islands","VA"=>"Virginia","WA"=>"Washington","WV"=>"West Virginia","WI"=>"Wisconsin","WY"=>"Wyoming","AB"=>"Alberta","BC"=>"British Columbia","MB"=>"Manitoba","NB"=>"New Brunswick","NL"=>"Newfoundland and Labrador","NT"=>"Northwest Territories","NS"=>"Nova Scotia","NU"=>"Nunavut","ON"=>"Ontario","PE"=>"Prince Edward Island","QC"=>"Quebec","SK"=>"Saskatchewan","YT"=>"Yukon","OO"=>"Other");
$define_character = array("m"=>"Medic","g"=>"Gunner","r"=>"Rifleman","s"=>"Sniper","e"=>"Engineer");

//Start HTML Table
print('<table cellspacing=0 cellpadding=0 width=100%>');
//-----------------------------------
//Get Info
//-----------------------------------
$main_result = mysql_query("SELECT m.id, m.name, m.email, m.joined, m.bday_day, m.bday_month,
    m.bday_year, x.icq_number, c.field_1, c.field_2, c.field_3, c.field_4
FROM ibf_members AS m
INNER JOIN ibf_member_extra AS x ON m.id = x.id
INNER JOIN ibf_pfields_content AS c ON m.id = c.member_id
WHERE mgroup=7
ORDER BY id");
while($main = mysql_fetch_array($main_result)) { //while you have records available from the SELECT query
    $id = $main['id'];
    $name = $main['name'];
    $email = $main['email'];
    $join_date = $main['joined'];
    $bday_day = $main['bday_day'];       
    $bday_month = $main['bday_month'];
    $bday_year = $main['bday_year'];     
    $icq = $main['icq_number'];
    $stats = $main['field_1'];
    $character = $main['field_2'];
    $country = $main['field_3'];
    $state = $main['field_4'];

function getAge ($bday, $bmon, $byr) {
    $ynow = date('Y');
    
    $age = $ynow - $byr;
        // format birth month and day as "0901"
    $bmd = sprintf ('%02d%02d', $bmon, $bday);
        // format today monthand day in same way
    $mdnow = date('md');
    
    if ($bmd > $mdnow) $age -= 1;   // sub 1 from age if not there yet
    
    return $age;
}

// call the function to get the age
$age = getAge ($bday_day, $bday_month, $bday_year);

echo $age;


echo ("<tr><td>$name </td><td>JOINED $join_date</td><td><img src='images/flags/$define_country[$country].gif' border=1 alt='$define_country[$country]'> <img src='images/flags/$define_state[$state].gif' border=1 alt='$define_state[$state]'></td><td><a href='http://web.icq.com/whitepages/add_me?uin=$icq_number&action=add'><font size='-1'>$icq_number</font></a></td><td><a href='mailto:$email'><font size='-1'>Email</font></a></td><td>AGE $age</td><td><a href='$stats'><font size=-1><b><u>JO Stats</u></b></a></td><td>$define_character[$character]</td></tr>");
}


//Finish the HTML table
print('</table>');

?>


#15 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 13 October 2006 - 08:06 PM

you've wrapped your function in your 'while' loop - meaning it'll get redeclared on each iteration.

move the function to the top of your script - underneath the

<?php
require "forums/conf_global.php"; //because this file will not be located in the forums directory.
?>

will do the trick.

"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#16 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 08:13 PM

argh, now i have extra numbers!

#17 MrLarkins.com

MrLarkins.com
  • Members
  • PipPip
  • Member
  • 20 posts

Posted 13 October 2006 - 08:17 PM

lol, i'm such a bonehead sometimes...its all good, thanks for the help, this topic is done...




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users