未定义的变量:名称PHP

时间:2016-06-04 02:58:19

标签: php variables undefined

我是php的初学者,我无法将获取的数据打印到html标签的标签内容中。

我正在运行PHP脚本,并且不断收到错误:

  

注意:未定义的变量:第19行的C:\ wamp64 \ www \ voting \ stack.php中的名称

<label ><?php echo $name;?> </label>// line no. 19

<?php       
if(isset($_POST["submit"]))
{
$id=$_POST["id"];
$sql="SELECT NAME from register WHERE ID='$id'";
$result=$con->query($sql);
if($result->num_rows==1)
{
if($row=$result->fetch_assoc())
{
$name=$row['NAME']; 
}
else
{
echo "record not found";
}
}
else
{
echo"error";
}
}
?>

1 个答案:

答案 0 :(得分:1)

您需要在if语句之外使用变量。它不存在于声明它的代码块之外。

如果首先没有在括号内提及,则无法访问括号内的某些内容。在这种情况下,您已经在if块中声明了所有内容。因此,如果您想访问if语句之外的任何变量,则需要先在if语句之外声明或使用它。

试试这个......

<?php
$name = "";
if(isset($_POST["submit"]))
{
    $id=$_POST["id"];
    $sql="SELECT NAME from register WHERE ID='$id'";
    $result=$con->query($sql);
    if($result->num_rows==1)
    {
        if($row=$result->fetch_assoc())
        {
            $name=$row['NAME'];
        }
        else
        {
            echo "record not found";
        }
    }
    else
    {
        echo"error";
    }
}
?>
<label ><?php echo $name;?> </label>// line no. 19

这可能会更好地证明这一点......

if(somecondition){
$dog = 'spot';
echo $dog; //Works because we're in the if statement
}
echo $dog; //Doesn't work because we're outside the if statement and we didn't have a $dog before the if statement.