Monday, June 4, 2012

Get Age from Birth Day php






Get Age from Birth Day php 


Create table with birth days as follows birth_day field data type is date name the table as"person".

CREATE TABLE IF NOT EXISTS `person` (
  `id` int(45) NOT NULL AUTO_INCREMENT,
  `FirstName` varchar(15) DEFAULT NULL,
  `LastName` varchar(15) DEFAULT NULL,
  `birth_day` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;



PHP Codes to display age from birth is bellow.

<?php
$host="localhost";
$username="root";
$password="";
$db_name="my_database";
$tbl_name="person";


mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT id,FirstName,LastName,year(curdate())-year(birth_day) as Age FROM $tbl_name";

$result=mysql_query($sql);

?>
<table  align="center"  bgcolor="#15475c">
<tr bgcolor="#ddeef5">
<td align="center" ><strong>ID</strong></td>
<td align="center" "><strong>First Name</strong></td>
<td  align="center" "><strong>Last Name</strong></td>
<td align="center" "><strong>Age</strong></td>
</tr>

<?php
while($rows=mysql_fetch_array($result)){

?>
<tr bgcolor="#ddeef5">
<td bgcolor="#FFFFFF"><?php echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['FirstName']; ?></td>
<td align="center" bgcolor="#FFFFFF"><?php echo $rows['LastName']; ?></td>
<td align="center" bgcolor="#FFFFFF"><?php echo $rows['Age'];?></td>

</tr>

<?php

}
mysql_close();
?>

</table>

You will see the final table like this.

ID First Name Last Name Age
1 Scarl Johan 48
2 Clooneer Henderson 38
3 Katena Daviddson 24

No comments:

Post a Comment