根据输入的出生日期计算年龄时未定义的指数


Undefined index when calculating age from an inputted birthdate

我是这个网站的新手,我发现了一些与我的系统错误有关的问题,但不幸的是,他们无法修复错误。我正在为我的capstone项目创建一个离线的基于web的信息系统,我不明白为什么P_Bday是未定义的。。这是我的代码

这是我输入生日的代码:

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

这是我计算年龄的代码:

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"];

我在这里调用我的函数,它应该根据输入的出生日期显示计算出的年龄:

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

每次我运行代码时,它都会说:

注意:中的未定义索引:p_BdayC:''examplep''htdocs''PISGDH''recordcorner''RecordEntry''addPatient.php联机47

如果在通过POST发送任何内容之前,行$dob = $_POST["P_Bday"];正在页面上运行,则$_POST[foo]无效。

将行更改为:

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

或者:

$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;

Undefined index错误的调试非常简单。从错误消息C:'xampp'htdocs'PISGDH'recordclerk'RecordEntry'addPatient.php中提到的文件开始,转到错误消息line 47中提到的行,在该行P_Bday上找到有问题的未定义索引,并且绝对确定地知道,到目前为止,在代码中,您还没有为该变量定义索引。您可以通过反向代码来尝试找出您的错误。错误可能是打字错误(您使用了错误的大小写/变量名),也可能是您忘记正确初始化变量。

避免未定义变量/索引错误的最佳方法是始终初始化并尽早初始化。在少数无法确保变量正确初始化的情况下(,例如使用$_POST/$_GET或其他受客户端输入控制的外部变量),您希望使用isset来避免错误,这样您就可以合并空值或编写逻辑,以防止在用户出错时代码继续使用未初始化的值。

示例

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

$_POST/$_GET的几种良好初始化技术

对于"始终初始化并尽早初始化";在处理用户输入时,要为表单中的预期输入设置一组默认值,并根据该值进行初始化,以免陷入这种陷阱。

示例

$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;
}

您在调用函数后声明变量$dob。您必须在函数调用之前声明您的变量,并使用如下条件语句:请按如下方式编写代码:

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;
    }
}