明确定义的未定义变量

时间:2013-11-20 02:59:14

标签: php html mysql

有人可以告诉我为什么上面发布的代码的上半部分工作得很好,但最后一段代码只给我语法错误“Undefined Variable $ secQuestion”

$result = mysql_query("select id, firstName, lastName, emailAddress, phoneNumber, underGradSchoolId, gradSchoolId, securityQuestionId from usertable where id=$id");

while($row = mysql_fetch_assoc($result)){
$id=$row["id"];
$firstName=$row["firstName"];
$lastName=$row["lastName"];
$email=$row["emailAddress"];
$phone=$row["phoneNumber"];
$undergradid=$row["underGradSchoolId"];
$gradid=$row["gradSchoolId"];
$securityquestionid=$row["securityQuestionId"];
}

$showUnderGrad="select schoolName from schooltable
where id=$undergradid
";
$result=mysql_query($showUnderGrad,$conn) or die (mysql_error());

while($row = mysql_fetch_assoc($result)){
$underGrad=$row["schoolName"];
}

$showGradSchool="select schoolName from schooltable
where id=$gradid
";
$result=mysql_query($showGradSchool,$conn) or die (mysql_error());

while($row = mysql_fetch_assoc($result)){
$grad=$row["schoolName"];
}

但是这给了我一个变量未定义的错误:

$showSec="select id, securityQuestion, securityAnswer from securityquestiontable
where id=$securityquestionid
";
$result=mysql_query($showSec,$conn) or die (mysql_error());

while($row = mysql_fetch_assoc($result)){
$secQuestion=$row["securityQuestion"];
$secAnswer=$row["securityAnswer"];
}

1 个答案:

答案 0 :(得分:1)

您的查询没有返回任何行,因此while(){...}块永远不会运行。 它至少需要运行一次才能定义变量。 您可以在while循环之外(和之前)初始化它们,如下所示:

//add the following 2 lines
$secQuestion=null;
$secAnswer=null;

while($row = mysql_fetch_assoc($result)){
$secQuestion=$row["securityQuestion"];
$secAnswer=$row["securityAnswer"];
}