1

I am new in this site, and i found some questions that are connected to my system error but unfortunately they can't fix the error. I am creating an offline web-based information system for my capstone project and I don't understand why P_Bday is undefined.. Here is my code

This is my code for inputting Birthdate:

input type="text" id = "P_Bday" name = "P_Bday" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" data-mask placeholder="dd/mm/yyyy" required

And here's my code for calculating age:

function ageCalculator($dob){
    if(!empty($dob)){
        $birthdate = new DateTime($dob);
        $today   = new DateTime('today');
        $age = $birthdate->diff($today)->y;
        return $age;
    }
    else{
        return 0;
    }
}

$dob = $_POST["P_Bday"];

And I call my function here, where it should display the calculated age depending on the inputted birthdate:

input type='text' name = 'P_Age' id='disabledTextInput' class='form-control' value='".ageCalculator($dob)."' readonly

Every time I ran my code it says:

Notice: Undefined index: P_Bday in C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php on line 47

Ben
  • 8,894
  • 7
  • 44
  • 80
  • Can you show us the
    tag at the top of your code ?
    – Nirnae Nov 09 '15 at 15:21
  • Welcome to SO. Please visit the [help] to see how to ask. Also get help formatting markdown [here](http://stackoverflow.com/editing-help) - Start by removing the `
    `and instead indent 4 spaces.
    – mplungjan Nov 09 '15 at 15:22
  • Is the second input shown on the same page as the first? If you show it before the form is submitted, there will be no POST data available – Jeff Lambert Nov 09 '15 at 15:23
  • http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index – mplungjan Nov 09 '15 at 15:25

3 Answers3

0

If the line $dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST, then $_POST[foo] is invalid.

Change the line to:

if(isset($_POST["P_Bday"])) $dob = $_POST["P_Bday"];
    else $dob = null;

Or:

$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;
Ben
  • 8,894
  • 7
  • 44
  • 80
  • thanks Ben Pearl Kahan it worked, but the age resulted to "0" every time I input the birthday – Celso Funelas Nov 09 '15 at 15:37
  • Could you put `var_dump($dob);` after the line above so we can see what the output of `$dob` is? – Ben Nov 09 '15 at 15:39
  • I mean, look at it when something has been posted - after you've submitted the form! The reason why I ask is because format of the `datetime` might be incorrect to process the function. – Ben Nov 09 '15 at 15:45
0

An Undefined index error is pretty simple to debug. You start at the file mentioned in the error message C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php and go to the line mentioned in the error message line 47 and find the undefined index in question on that line P_Bday and know with absolute certainty that up to this point in your code you have not defined that index for that variable. You can work your way backwards through the code to try and figure out your mistake. The mistake can be a typo (you used the wrong case/variable name) or it can be that you just forgot to initialize the variable properly.

The best way to avoid undefined variable/index errors is to initialize always and initialize early. In the few cases where you cannot be sure that variables are properly initialized (for example with $_POST/$_GET or other external variables under control of client input) you want to use isset to avoid the error and that way you can coalesce null values or write logic that prevents the code from continuing with an uninitialized value in case of user error.

Example

if (!isset($_POST['P_Bday'])) {
    die("You forgot to fill out your birthday!");
} else {
    echo "Yay!";
}

Some good initialization techniques with $_POST/$_GET

A good best practice for "initialize always and initialize early" when dealing with user input is to setup a default set of values for the expected input from your form and initialize from that in order not to fall into this trap.

Example

$defaultValues = [
    'P_Bday'  => null,
    'Option1' => 'default',
    'Option2' => 1,
];
/* Let's say the user only supplied Option1 */
$_POST = ['Option1' => 'foo'];
/* This makes sure we still have the other index initialized */
$inputValues = array_intersect_key($_POST, $defaultValues) + $defaultValues;

/**
 * Now you can pass around $inputValues safely knowing all expected values
 * are always going to be initialized without having to do isset() everywhere
 */

doSomething(Array $inputValues) {
    if (!$inputValues['P_Bday']) { // notice no isset() check is necessary
        throw new Exception("You didn't give a birthday!!!");
    }
    return (new DateTime)->diff(new DateTime($inputValues['P_Bday']))->y;
}
Community
  • 1
  • 1
Sherif
  • 11,786
  • 3
  • 32
  • 57
0

You are declaring the variable $dob after calling function. You have to declare your variable before function call and also use conditional statement like following: Please write your code as follows:

if(isset($_POST["P_Bday"])){
    $dob = $_POST["P_Bday"];
} else {
    $dob ="";
}
function ageCalculator($dob){
    if(!empty($dob)){
        $birthdate = new DateTime($dob);
        $today   = new DateTime('today');
        $age = $birthdate->diff($today)->y;
        return $age;
    }
    else{
        return 0;
    }
}
Ben
  • 8,894
  • 7
  • 44
  • 80