tags:

views:

67

answers:

3

I'm a beginner in PHP. 2 days ago I write few lines of code that was working, but yesterday, it wasn't anymore. The code was:

<body>
    <form method='post' action='test.php'>
        name <input type='text' id='txtName'/>
        age <input type='text' id='txtAge'/>
        <input type='submit'/>
        <hr/>
        name <?php echo $_POST['txtName']; ?>
        age <?php echo $_POST['txtAge']; ?>
    </form>
</body>

What it does is only to show the value of text boxes, but it's not working. Why?

+5  A: 

Use name attribute on your input tags not ID for your php post variables:

<body>
<form method='post' action='test.php'>
    name <input type='text' name='txtName'/>
    age <input type='text' name='txtAge'/>
    <input type='submit'/>
    <hr/>
    name <?php echo $_POST['txtName']; ?>
    age <?php echo $_POST['txtAge']; ?>
</form>

Chris
Use both name and id I would recommend :) Name is a must, of course but I think it would be alright to give a unique id to all input tags as well.
Richard Knop
The ids would be useless unless you require the elements to be targets for some DOM fiddling or as selectors for CSS. Personally, I hate litering html with IDs that serve no purpose.
Marc B
Ids in forms are actually serving a great purpose in terms of accessibility. Using <label for="someID">some input</label><input id="someID" name="something" /> is great for users using screen readers.
Chris
+2  A: 

Use name instead of id:

<body>
    <form method='post' action='test.php'>
        name <input type='text' name='txtName'/>
        age <input type='text' name='txtAge'/>
        <input type='submit'/>
        <hr/>
        name <?php echo $_POST['txtName']; ?>
        age <?php echo $_POST['txtAge']; ?>
    </form>
</body>
Edward Mazur
+1  A: 
  • First confirm that this code is in same file(test.php) as described in form's action attribute because you are using same file for input and display posted data.

  • In $_POST['name'], it uses name of input field not id.

If you still want to keep id in form attributes:

<body>
    <form method='post' action='test.php'>
        name <input type='text' name='userName' id='txtName'/>
        age <input type='text' name='userAge' id='txtAge'/>
        <input type='submit'/>
        <hr/>
        name <?php echo $_POST['userName']; ?>
        age <?php echo $_POST['userAge']; ?>
    </form>
</body>
NAVEED