未定义变量:名称 PHP

undefined variable: name PHP

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

我是 运行 一个 PHP 脚本,并且不断收到如下错误:

Notice: Undefined variable: name in C:\wamp64\www\voting\stack.php on line 19

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

您需要在 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.