Jump to content


Photo

Calculating Age: why doesn't this work? Please Help


  • Please log in to reply
7 replies to this topic

#1 crackerjax

crackerjax
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 22 October 2006 - 06:22 PM

I've only been working with PHP for about a month so this might be something really simple.  I've got a form calling to a another file with a birthday.  I want to know how old the person is.  Then I want to know if they're half way to their next birthday.  So if they're 182 days past thier birthday, I know, or less than 182 from their next.  Thats the logic I'm trying to use.

The pages are up at www.nickjohnsonphoto.com/short3.php and
www.nickjohnsonphoto.com/short4.php

I commented out the mysql part because I'm putting that on hold until this gets worked out, but it seems to work correctly now.

Short 3 has the same value for the radios to keep debugging simple. ignore that.

The issue I'm having now is the logic of the halfOver function if statements isn't working right.  Does anyone understand what I'm trying to do?

here is the code: short 3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Untitled</title>
</head>

<body>
<h1>Instant insurance estimate</h1>
<h3>Please enter the following information</h3>
<form method="get"
      action="short4.php">
  <table>
    <tr>
      <td>Birth Date:
	    <select name=birthMonth>
		  <option value=1>January</option>
		  <option value=2>February</option>
		  <option value=3>March</option>
		  <option value=4>April</option>
		  <option value=5>May</option>
		  <option value=6>June</option>
		  <option value=7>July</option>
		  <option value=8>August</option>
		  <option value=9>September</option>
		  <option value=10>October</option>
		  <option value=11>November</option>
		  <option value=12>December</option>
		</select>
		<select name=birthDay>
<?php
	      $i = 1;
	 	  while ($i <= 31)
		    {
			  echo "<option value=$i>$i</option>";
			  $i++;
			}
		echo "</select>";
		echo "<select name=birthYear>";
		  $j = 1925; //starting year
		  while ($j <= 1988) //ending year
		    {
			  echo "<option value=$j>$j</option>";
			  $j++;
			}
?>
      </td>
	</tr>
	<tr>
	  <td>
	    Smoker: Yes
	    <input type=radio name="smoker" value="no">
		No
		<input type=radio name="smoker" value="no">
	  </td>
	  <td>
	    Male: 
	    <input type=radio name="gender" value="male">
		Female: 
		<input type=radio name="gender" value="male">
	  </td>
	</tr>
  </table>
  <button type=submit name="submit">Submit</button>
</form>
</body>
</html>

and short4:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Untitled</title>
</head>

<body>
<?php
  
//find difference between 2 dates function
//take from http://www.developertutorials.com/tutorials/php/calculating-difference-between-dates-php-051018/page1.html
$dob="$birthMonth/$birthDay/$birthYear";

function dateDiff($dformat, $endDate, $beginDate)
  {
    $date_parts1=explode($dformat, $beginDate);
    $date_parts2=explode($dformat, $endDate);
    $start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
    $end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
    return $end_date - $start_date;
  }

//use the above function to turn the age from then (DOB) to NOW into a # of years old, rounded down
$ageInYears=floor(dateDiff("/", date("m/d/Y", time()), $dob)/365.25);
$halYearOlder = 0;

echo "<br>Age in Years before addition<br>";
echo $ageInYears;

//Half birthday determininininer
function overHalf ($birthMonth, $birthDay, $currentMonth, $currentDay)
{
  global $halfYearOlder;
  if ($birthMonth > $currentMonth)
    {
      $daysTill = (30.416 * ($birthMonth - $currentMonth) + ($birthDay - $currentDay));
      if ($daysTill < 182)
        {
          echo "<br>$daysStill<br>";
          $ageInYears++;
          $halfYearOlder = 1;
        }
    }
    else if ($birthMonth < $currentMonth)
      {
        $daysSince = (30.416 * ($currentMonth - $birthMonth) + ($currentDay - $birthDay));
        if (daysSince > 182)
          {
            echo "<br>$daysStill<br>";
            $ageInYears++;
            $halfYearOlder = 6; //6 is just so i know its not the 1 from before.  Another debug value.
          }
      }
      else if ($birthMonth == $currentMonth)
        {
          $halfYearOlder = 0;
        }
}

//so now its time to bring up the DB

// open connection to MySQL server
mysql_connect("localhost", "nickj3_guest", "pass") or die(mysql_error());
mysql_select_db("nickj3_shortInsForm") or die(mysql_error());


overHalf($birthMonth,$birthDay,date(n),date(j));

echo "<br>Now the age is: ";
echo $ageInYears;
echo "<br>the state of halfover is: ";
echo $halfYearOlder;
echo "<br>";

// Determine our Query
echo $gender;
echo "<br>";
echo $smoker;

echo "<br>";
echo (dateDiff("/", date("m/d/Y", time()), $dob)/365.25);
echo "<br>";

/*
if ($gender == "male")
  {
    if ($smoker == "no")
	  {
	    $query="SELECT 20yrSuPreMax FROM maleNonSmoker WHERE age = 6";
      } 
  }

// Retrieve all the data from the "example" table
$result = mysql_query($query)
or die(mysql_error());  

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );

echo "Name: ".$row[0];


echo "<br>This person is $ageExploded[0] years old and $ageExploded[1]";

mysql_free_result($result);
mysql_close ("localhost", "nickj3_guest", "pass");

*/
?>
</body>
</html>


#2 obsidian

obsidian
  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 22 October 2006 - 06:53 PM

ok, here's a sample way to check age. mod it however you need to get it to work with your mysql query:
<?php
// requires $bday in YYYY-MM-DD format
// returns an array with 2 values: 1) age and 2) boolean T or F if they are half way to next bday
function getAge($bday) {
  $time = time();
  $bdts = strtotime($bday);
  $year = 60 * 60 * 24 * 365;
  $agets = abs($time - $bdts);
  $age  = floor($agets / $year);
  $bal  = $agets % $year;
  $days = floor($bal / (60 * 60 * 24));
  $half = $days > 182 ? true : false;
  return array($age, $half);
}

$bday = "1980-02-15";
$age  = getAge($bday);
echo "$age[0] years old. You are " . ($age[1] ? '' : 'not ') . "halfway to your next birthday!";
?>

hope this helps!
You can't win, you can't lose, you can't break even... you can't even get out of the game.

<?php
while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

#3 crackerjax

crackerjax
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 22 October 2006 - 09:24 PM

try www.nickjohnsonphoto.com/short6.php which goes to short5.php

It always says I'm over half.  Something seems wrong.

#4 obsidian

obsidian
  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 23 October 2006 - 01:18 AM

worked fine for me. put in something like September or August. remember, you're figuring half way will always be 6 months back from the current date.
You can't win, you can't lose, you can't break even... you can't even get out of the game.

<?php
while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

#5 crackerjax

crackerjax
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 23 October 2006 - 01:49 AM

I'm getting erratic results.  Look at these urls:

http://www.nickjohns...er=male&submit=
Above is born 1925, definitely not 36 yrs old.
http://www.nickjohns...er=male&submit=
Above is 1986, and age 19 is appropriate.

From the 36 years old problem I gather that the cut off is 1970 birthyear, which is the case.  If they're born before 1970, I get 36 yrs and a half for my response.  Here is the actual code I have.

My only guess is that the numbers are getting so large after 1970 its falling apart.  Ideas?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Untitled</title>
</head>

<body>
<?php
  
//starting froms scratch on short5
//using the script found on http://www.phpfreaks.com/forums/index.php/topic,112347.0.html


// requires $bday in YYYY-MM-DD format
// returns an array with 2 values: 1) age and 2) boolean T or F if they are half way to next bday
function getAge($bday)
  {
    $time = time();
    $bdts = strtotime($bday);
    $year = 60 * 60 * 24 * 365;
    $agets = abs($time - $bdts);
    $age  = floor($agets / $year);
    $bal  = $agets % $year;
    $days = floor($bal / (60 * 60 * 24));
    $half = $days > 182 ? true : false;
    return array($age, $half);
  }

$bday = "$birthYear-$birthMonth-$birthDay";
$age  = getAge($bday);
echo "$age[0] years old. You are " . ($age[1] ? '' : 'not ') . "halfway to your next birthday!";

?>
</body>
</html>


#6 crackerjax

crackerjax
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 23 October 2006 - 01:54 AM

Interesting thing I just read:
http://us3.php.net/strtotime

The function expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT), relative to the timestamp given in now, or the current time if none is supplied.

That might explain the 1970 thing.  We need a better function.

#7 crackerjax

crackerjax
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 23 October 2006 - 01:08 PM

How about someone look at the original code and tell me if that makes sense.  Any help is appreciated.

#8 crackerjax

crackerjax
  • New Members
  • Pip
  • Newbie
  • 7 posts

Posted 23 October 2006 - 02:23 PM

Fixed.  My original code was just sloppy.  Missing a $ here and there.  :P




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users