$ _POST的未定义索引(noob问题!)

时间:2011-05-29 19:25:28

标签: xampp php

  

可能重复:
  PHP: “Notice: Undefined variable” and “Notice: Undefined index”

我只是在学习PHP而且我一直收到一个未定义的索引错误。我正在学习的这本书有一个HTML表单和一个处理表单的PHP页面,使用以下格式:

<!-- The form fields are all set up something like this -->
<input type="text" id="howlong" name="howlong" /><br />

// The PHP starts with one line like this for each of the form fields in the HTML
$how_long = $_POST ['howlong'];

// And there is one line for each one like this to output the form data: 
echo ' and were gone for ' . $how_long . '<br />';

我正在使用的示例包含大约12个表单字段。

奇怪的是,并非所有变量都会抛出此错误,但我看不到它的模式。

我已经检查过所有HTML字段名称与我输入的PHP $ _POST变量名称相匹配,并且我已经确定当我填写表单并提交表单时,所有字段都填充了某些内容。有趣的是,可以为本书下载的完整代码也会引发此错误。

我意识到这段代码可能无法反映最佳实践,它来自本书的第一章,显然我是一个菜鸟:)

如果它有所不同,我在XAMPP 1.7.4上使用PHP 5.3.5和Windows 7 Home Premium。

3 个答案:

答案 0 :(得分:6)

请记住在表单标记上将方法设置为POST ...

继承了我曾经尝试过的代码,这对我有用:

在名为test.php的文件中:

<html>
  <body>
    <form method="POST" action="testProc.php">
      <input type="text" id="howlong" name="howlong" /><br/>
      <input type="submit" value="submit"/>
    </form>
  </body>
</html>

并在testProc.php中:

<?php
if (isset($_POST)) {
  if (isset($_POST["howlong"])){
    $howlong = $_POST['howlong'];
    echo ' and were gone for ' . $howlong . '<br />';
  }
}
?>

就像建议一样,要使用样式表进行显示操作,我建议将表单放在表格中,如下所示:

<html>
  <body>
    <form method="POST" action="testProc.php">
      <table>
        <tbody>
          <tr>
            <th>
              <label for="howlong">How long? :</label>
            </th>
            <td>
              <input type="text" id="howlong" name="howlong" />
            </td>
          </tr>
          <tr>
            <input type="submit" value="submit"/>
          </tr>
        </tbody>
      </table>
    </form>
  </body>
</html>

希望你能用这个......

答案 1 :(得分:2)

您需要检查表单是否已提交,然后您可以尝试使用$ _POST数组,因此您应该将此代码放在上面:

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

其中“发送”是提交按钮的名称

答案 2 :(得分:1)

您可以使用isset()函数测试是否设置了变量。

此外,并非所有HTML表单元素都会在所有情况下都发布值。常见的例子是复选框;未选中的复选框不会成为发布回服务器的数据的一部分。因此,您期望设置的$ _POST元素将不会。