简体   繁体   English

从输入的出生日期计算年龄时的不确定索引

[英]Undefined index when calculating age from an inputted birthdate

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 我正在为我的顶点项目创建一个基于Web的脱机信息系统,但我不明白为什么未定义P_Bday 。这是我的代码

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 通知:未定义指数:P_Bday在C:\\ XAMPP \\ htdocs中\\ PISGDH \\ recordclerk \\在线47RecordEntry \\ addPatient.php

If the line $dob = $_POST["P_Bday"]; 如果行$dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST , then $_POST[foo] is invalid. 在通过POST发送任何内容之前正在页面上运行,则$_POST[foo]无效。

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;

An Undefined index error is pretty simple to debug. Undefined index错误非常易于调试。 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. 您从错误消息C:\\xampp\\htdocs\\PISGDH\\recordclerk\\RecordEntry\\addPatient.php提到的文件开始,然后转到错误消息line 47行中提到的line 47并在该行P_Bday和以下P_Bday找到有问题的未定义索引绝对可以肯定的是,到目前为止,在代码中您还没有为该变量定义该索引。 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. 在少数情况下,您不能确定变量是否已正确初始化( 例如,在客户端输入的控制下使用$_POST / $_GET或其他外部变量 ),您可以使用isset来避免错误,并且可以合并空值或编写逻辑,以防止用户出错时代码以未初始化的值继续。

Example

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

Some good initialization techniques with $_POST / $_GET $_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;
}

You are declaring the variable $dob after calling function. 您在调用函数后声明了变量$ dob。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM