phpvariablesundefined

undefined variable: name PHP


I am a beginner of php i can't print a fetched data into the label content at the html tag.

I am running a PHP script, and keep getting errors like:

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

Solution

  • You need to use your variable outside your your if statement. It doesn't exist outside of the block of code that it's declared in.

    You can't access something inside a set of brackets if it wasn't mentioned outside your brackets first. In this case, you've declared everything inside your if block. So if you wanted to access any of your variables outside your if statement, you need to declare or use it outside your if statement first.

    Try this...

    <?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
    

    This might demonstrate the point better...

    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.