Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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'];
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading