我在这些变量中得到一个未定义的索引错误:id,subj,mid,fin。我已正确定义它们,我不知道我的代码有什么问题。我认为问题在于我定义了这4个变量的代码的位置。请帮忙?感谢。
echo "
<form action=editgrades.php method=post>
ID: <input type='text' name='id' maxlength='5' size='3'>
Subject: <input type='text' name='subj' maxlength='3' size='3'>
Midterm: <input type='text' name='mid' maxlength='3' size='3'>
Finals: <input type='text' name='fin' maxlength='3' size='3'>
<input type='submit' name='submit' value='Update'>
</form>
";
$mysqli = mysqli_connect("localhost", "root", "", "school");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "select * from studentgrades";
}
$id = $_POST['id'];
$subject = $_POST['subj'];
$midterm = $_POST['mid'];
$finals = $_POST['fin'];
$average = ($midterm + $finals) / 2;
if ($average >= 70) {
$remarks = 'Passed';
} else {
$remarks = 'Failed';
}
$res = mysqli_query($mysqli, $sql);
if ($res) {
$sql1 = "
update studentgrades set Subject = " . $subject . ",
Midterm = " . $midterm . ",
Finals = " . $finals . ",
Average = " . $average . ",
Remarks = " . $remarks . "
where ID = " . $id . "
";
$res1 = mysqli_query($mysqli, $sql1);
if ($res1) {
echo "
Grades updated successfully.
<br><br>
";
}
}
答案 0 :(得分:0)
这是因为您在提交表单之前尝试使用POST变量。
它没有抱怨$id
。 “未定义的索引”表示您尝试使用不存在的数组的键,在本例中为$_POST
数组。
在尝试使用索引之前检查索引是否已设置:
$id = isset($_POST['id']) ? $_POST['id'] : null;
$subject = isset($_POST['subj']) ? $_POST['subj'] : null;
etc...
或者只是关闭错误报告(不推荐)
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
答案 1 :(得分:0)
这是您的问题 - 您不检查是否设置了帖子。因此,如果您在提交表单之前调用此页面,那么您将尝试调用任何$ _POST var的未定义索引。
做这样的事情:
if(isset($_POST['id']))
{
$mysqli = mysqli_connect("localhost", "root", "", "school");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else{
$sql = "select * from studentgrades";
}
$id = $_POST['id'];
$subject = $_POST['subj'];
$midterm = $_POST['mid'];
$finals = $_POST['fin'];
$average = ($midterm+$finals)/2;
if($average >= 70){
$remarks = 'Passed';
}
else {
$remarks = 'Failed';
}
$res = mysqli_query($mysqli, $sql);
if ($res) {
$sql1 = "
update studentgrades set Subject = ".$subject.",
Midterm = ".$midterm.",
Finals = ".$finals.",
Average = ".$average.",
Remarks = ".$remarks."
where ID = ".$id."
";
$res1 = mysqli_query($mysqli, $sql1);
if ($res1){
echo "
Grades updated successfully.
<br><br>
";
}
}
尽管isset($ _ POST ['id']))可以用任意数量的方式替换,以验证表单是否已提交。
附注 - 您应该在输出任何html之前运行所有后期处理,以防您需要根据发布结果修改标题。如果此代码需要执行以下操作:
if($id == '')
{
header('location: /');
exit;
}
它会告诉你标题已经发送并给你另一个错误。