PHP $_POST not working "Undefined Variable" after inputting data

Advertisements

im an IT student currently studying PHP, JS, and HTML/CSS can someone help me why this causes an error "Undefined variable: name" from that span line (even after submitting "name" in forms). thank you very much

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                            <p> Name: <input type="text" name="name" placeholder="Input Name Here..."></p>
                            <span><?php echo $name?></span>
                            <button type="submit">Submit</button> 
                            </form>   

PHP

if($_SERVER["REQUEST_METHOD"] == "POST"){
    $name = $_POST['name'];
    }

>Solution :

In the first block of code the variable $name isn’t declared yet.

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                            <p> Name: <input type="text" name="name" placeholder="Input Name Here..."></p>
                            <!-- remove the below line -->
                            <span><?php echo $name?></span>
                            <button type="submit">Submit</button> 
                            </form>  

Or you can define $name to be an empty string so it’s defined even without a POST request being sent:

<?php
$name = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $name = $_POST['name'];
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                            <p> Name: <input type="text" name="name" placeholder="Input Name Here..."></p>
                            <span><?php echo $name; ?></span>
                            <button type="submit">Submit</button> 
                            </form>   

Leave a ReplyCancel reply