为什么此代码不再显示我的文本框的值?

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?

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>

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