0

As a newbie in programming I need your help in building a small app which will auto calculate age from dob in the form fields below with php code! Is there a way to achieve that?

My html code is:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>form practice</title>

</head>

<body>

    <div class="form2" id="form2" name="form2">

        <form action="php/form2.php" method="post" id="Personalinfo">

            <label for="fname">Name:</label>
            <input type="text" id="fname" name="firstname" placeholder="Client 
        Name..">

            <label for="lname">Lastname:</label>
            <input type="text" id="lname" name="lastname" placeholder="Client 
        Lastname..">

            <label for="dob">Birthday:</label>
            <input type="text" id="dob" name="dob" placeholder="yyyy/mm/dd..">

            <label for="age">Age:</label>
            <input type="text" id="age" name="age" placeholder="Client Age..">

            <input type="submit" name="submitForm2" value="Submit">

        </form>
    </div>

</body>

</html>

and my php code connecting to mysqli database:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST['submitForm2']))
{
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $dob = $_POST['dob'];
    $age = $_POST['age'];
    $sql = "INSERT INTO info (firstname, lastname, dob, age)
       VALUES ('{$firstname}', '{$lastname}', '{$dob}', '{$age}')";
    if ($conn->query($sql) === TRUE)
    {
        echo "New record created successfully";
    }
    else
    {
        echo "Error: " . $sql . "<br />" . $conn->error;
    }
}
else
{
    echo "Are you sure you enter a firstname and the name of your html submit 
       is submitForm";
}

$conn->close();
?>

I've searched on the internet and saw many examples calculating the age from dob but I couldn't find anything related in nesting the result in a form field named age, and also keeping the data in the database.

thanos_zach
  • 156
  • 4
  • 20

3 Answers3

0

You can get a good approximation of age by dividing the number of days by 365.25

I have it on good authority that there are people alive today aged over 47 - so you can't use PHP time values to store their date of birth (and if you are running on a 32 bit system you will have problems after 2038). Hence I would recommend doing the maths in the database. Indeed, the very first example in the MySQL manual illustrates this exact problem (and this method is not impacted by the rounding offset issue created when you divide by 365.25):

SELECT name, birth, CURDATE(),
TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
FROM pet;

But why are you storing the age in the database at all? It will be wrong at some point in the future. If you have the date of birth, you can calculate it when you retrieve the data.

symcbean
  • 47,736
  • 6
  • 59
  • 94
0
  • 1) You want to be using the PHP DateTime Class. You make two DateTime objects, one for the birthdate and one for right now, and then compare the two.

    With the assumption that we don't need to dig into timezone locales (which is completely possible but beyond the scope of this Q&A) this will give you an accurate result.

    DateTime Class Example:

    (PHP 5.6.29)

    $now =  new DateTime(); 
    
    // Note your SQL field should be a `DATE` column 
    // and formatted YYYY-MM-DD
    // assumed in this example $sqlData['dob'] = "2015-01-10";
    
    $birthday = new DateTime($sqlData['dob']);
    $age = $now->diff($birthday);
    //
    print "person is ".$age['y']." years old.";
    

    Full output of $age is below print_r($age):

    DateInterval Object
    (
        [y] => 2
        [m] => 6
        [d] => 23
        [h] => 5
        [i] => 34
        [s] => 11
        [days] => 935
     )
    

  • 2) As mentioned by Symcbean, you really don't need (and probably shouldn't) add the age of the person into the database, as :

    It will be wrong at some point in the future. If you have the date of birth, you can calculate it when you retrieve the data.

    -- symcbean


  • 3) While you get positive marks for using Object Orientated MySQL interactions, in PHP; you are still subject to SQL injection and potential database abuse. Instead of inserting PHP variables directly into your SQL, you want to be Using prepared statements and parameterized queries. Do it now before you get a chanceto learn any bad PHP habits!


Sources:

Martin
  • 22,212
  • 11
  • 70
  • 132
-1

Some friend gave the solution to my answer but unfortunately someone must erased it, so i'm giving the solution as i forestall to copy the script! Thanks a lot to one ho provided this script!

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>form practice</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){

        $("#dob").change(function(){
           var value = $("#dob").val();
            var dob = new Date(value);
            var today = new Date();
            var age = Math.floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000));
            if(isNaN(age)) {

            // will set 0 when value will be NaN
             age=0;

            }
            else{
              age=age;
            }
            $('#age').val(age);

        });

    });
    </script>
</head>

<body>

<div class="form2" id="form2" name="form2">

<form action="php/form2.php" method="post" id="Personalinfo">

<label for="fname">Name:</label>
<input type="text" id="fname" name="firstname" placeholder="Client 
Name..">

<label for="lname">Lastname:</label>
<input type="text" id="lname" name="lastname" placeholder="Client 
Lastname..">

<label for="dob">Birthday:</label>
<input type="text" id="dob" name="dob" placeholder="yyyy/mm/dd..">

<label for="age">Age:</label>
<input type="text" id="age" name="age" placeholder="Client Age..">

<input type="submit" name="submitForm2" value="Submit">


</form>
</div>

</body>
</html>
thanos_zach
  • 156
  • 4
  • 20
  • Your question stated using PHP and MySQL but your answer uses neither of these things and uses Javascript. – Martin Aug 02 '17 at 12:44
  • Martin the answer is not mine! someone else gave the script as an alternative way to do the thing i was asking for and for others help i just reproduce someone else's answer! thanks – thanos_zach Aug 02 '17 at 15:23
  • But you are asking a question about PHP / MySQL and you are saying [above] how the answer you want is Javascript!! Please clarify what you actually want and are actually trying to achieve! Whose answer it is doesn't matter, what matters is that you state this answer is the one you need even though it bears not direct relationship to the actual question you asked!!! – Martin Aug 02 '17 at 15:33
  • why the negative feedback? just some people look at the tree and miss the forest... – thanos_zach Aug 03 '17 at 08:29
  • If you're asking for tea it's not logical (and frustrating to those who provide you with tea) when you say all along that actually you wanted coffee. (*and the negative mark while I don't disagree with it, is not me*) – Martin Aug 03 '17 at 09:31