错误提示:出现未定义的索引

时间:2013-05-22 14:57:00

标签: php html mysql

我有三个复选框,用户应检查一个或两个选项。

当我选中2个选项时,会出现错误信息。

    $workshop1Day1 = $_POST["workshop1Day1"];
    $workshop2Day1 = $_POST["workshop2Day1"];
    $workshop3Day1 = $_POST["workshop3Day1"];


 $requete = "INSERT INTO Participant ( NameSurname,workshop1Day1,workshop2Day1,workshop3Day1)
                      VALUES ('$NameSurname', '$workshop1Day1', '$workshop2Day1', '$workshop3Day1')";
        $result = @mysql_query($requete);

错误:

Notice: Undefined index: workshop3Day1

然后我尝试了以下代码(例如:如果未选中复选框号3),则会出现相同的错误

  $workshop1Day1=' ';
  $workshop2Day1='';
  $workshop3Day1='';

  $workshop1Day1 = $_POST["workshop1Day1"];
  $workshop2Day1 = $_POST["workshop2Day1"];
  $workshop3Day1 = $_POST["workshop3Day1"];

if (isset($workshop1Day1)&& isset($workshop2Day1)&& !isset($workshop3Day1))
{

    $requete = "INSERT INTO Participant ( NameSurname,workshop1Day1,workshop2Day1,workshop3Day1)
                  VALUES ('$NameSurname', '$workshop1Day1', '$workshop2Day1', '$workshop3Day1')";
    $result = @mysql_query($requete);

我知道isset是解决方案但是如何?

1 个答案:

答案 0 :(得分:3)

您收到警告是因为您没有在源变量上运行isset,只是根据您分配给它的内容。

此行($workshop3Day1 = $_POST["workshop3Day1"];)将引发警告,因为该数组索引不存在。相反,在该行上使用isset,然后在if条件中使用该结果。像这样:

$workshop1Day1 = isset($_POST["workshop1Day1"]) ? $_POST["workshop1Day1"] : 0;
$workshop2Day1 = isset($_POST["workshop2Day1"]) ? $_POST["workshop2Day1"] : 0;
$workshop3Day1 = isset($_POST["workshop3Day1"]) ? $_POST["workshop3Day1"] : 0;

然后从isset条件中移除if