【问题标题】:PHP $_POST error Please Help me I am learning PHPPHP $_POST 错误请帮助我我正在学习 PHP
【发布时间】:2014-03-08 07:49:06
【问题描述】:

我正在学习 PHP。这是源代码。

<?php
$text = $_POST['text'];

echo $text;
?>

<form action="index.php" method="post">
<input type="text" name="text" />
    <input type="submit">
</form>

这是结果。我不知道问题出在哪里。

注意:未定义索引:第 2 行 C:\xampp\htdocs\faisal\index.php 中的文本

【问题讨论】:

  • 假设这是 index.php,当您第一次运行脚本时,没有任何内容被发布。当你提交它应该工作。
  • 该死的人,现在你有四个相等的答案!恭喜!

标签: php html mysql post undefined-index


【解决方案1】:

这意味着$_POST['text'] 中没有任何内容——而且在提交表单之前之后 之前不会有。需要使用isset()查看:

<?php
if(isset($_POST['text'])) {
    $text = $_POST['text'];

    echo $text;
}
?>

<form action="index.php" method="post">
<input type="text" name="text" />
    <input type="submit">
</form>

【讨论】:

    【解决方案2】:

    当您第一次访问该页面时,您的特殊变量“$_POST”为空,这就是您收到错误消息的原因。你需要检查一下里面有没有东西。

    <?php
    $text = '';
    if(isset($_POST['text']))
    {
      $text = $_POST['text'];
    }
    
    echo 'The value of text is: '. $text;
    ?>
    
    <form action="index.php" method="post">
      <input type="text" name="text" />
      <input type="submit">
    </form>
    

    【讨论】:

      【解决方案3】:

      $_POST['text'] 仅在提交表单时填充。因此,当页面首次加载时,它不存在并且您会收到该错误。作为补偿,您需要在执行 PHP 的其余部分之前检查表单是否已提交:

      <?php
      if ('POST' === $_SERVER['REQUEST_METHOD']) {
        $text = $_POST['text'];
      
        echo $text;
      }
      ?>
      
      <form action="index.php" method="post">
      <input type="text" name="text" />
          <input type="submit">
      </form>
      

      【讨论】:

        【解决方案4】:

        您可能必须确定表单是否已提交。

        <?php
        if (isset($_POST['text'])) {
            $text = $_POST['text'];
            echo $text;
        }
        ?>
        
        <form action="index.php" method="post">
        <input type="text" name="text" />
            <input type="submit">
        </form>
        

        您也可以使用$_SERVER['REQUEST_METHOD']

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {...
        

        【讨论】:

        • $_POST 始终设置。
        • 感谢您的建议...您当然完全正确。
        【解决方案5】:

        我们必须检查用户是否点击了提交按钮,如果是,那么我们必须设置 $test 变量。如果我们不使用 isset() 方法,我们总是会出错。

        <?php
        if(isset($_POST['submit']))
        {
          $text = $_POST['text'];
          echo $text;
        }
        ?>
        
        <form action="index.php" method="post">
        <input type="text" name="text" />
            <input type="submit" name="submit" value="submit">
        </form>
        

        【讨论】:

          猜你喜欢
          • 2021-03-30
          • 1970-01-01
          • 1970-01-01
          • 2012-10-02
          • 1970-01-01
          • 2020-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多