-1

I am just trying to get a text from text box and print it through POST method but i get the error Undefined index : name in 14th line

<html>
    <head>
        <title>Form with PHP </title>
    </head>
    <body>
        <form method = "post">
            <input type ="text" name="name">
            <input type="button" value="submit" id="submit">
        </form>

<?php
    $name=$_POST["name"];
    echo "my name is" .$name;


?>
</body>
</html>

3 Answers3

4

You need to use a conditional statement isset() on the form's input/name element in question, because you're running your entire code inside the same page.

The notice shows up on initial page load; that's why, because it hasn't been "set" yet.

Here:

if(isset($_POST['name'])){

    $name=$_POST["name"];
    echo "my name is" .$name;

}

or seperate your HTML form and PHP into seperate pages and set your action to action="handler.php". Yet, using a conditional isset() is best to be used either way.

You may also want to change your submit button to an submit type:

<input type="submit" value="submit" id="submit">

However, by the looks of your submit button type; it seems you may be using JS in conjunction with what you posted for code and did not include it in your question, therefore you should be posting that as well and/or make sure that you've properly set the attributes for it.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

If you load the page (without submitting the form), then $_POST['name'] will not exists, thus it gives that "undefined index" error message. You will need to make sure it exists prior to using it.

if (isset($_POST['name'])) {
    $name=$_POST["name"];
    echo "my name is" .$name;
}
Blah Argh
  • 304
  • 1
  • 4
0

You are using $name instead of $_POST["name"]. Correct way is:

if(!empty($_POST['name']))
    echo "my name is" .$_POST["name"];
Damaged Organic
  • 8,175
  • 6
  • 58
  • 84