【问题标题】:Can't get form value with PHP无法使用 PHP 获取表单值
【发布时间】:2017-10-27 09:18:29
【问题描述】:

我正在尝试使用 _POST 获取表单(文本字段)的值,并将其存储到文本文件中,但它不起作用。这是我的代码:

HTML

<form>
<input type="text" name="test" id="test" value="">
<input type="button" onclick="location.href='example.com/index.php?address=true';" value="ODOSLAŤ" />
</form>

PHP

if (isset($_GET['address'])) {

    $email = $_POST['test'];

    $myfile = fopen("log.txt","a") or die("Error.");
    fwrite($myfile, "\n".$email);

    // this prints nothing
    echo $email;  
  }

我无法获取该文本字段的值。 GET 和 POST 也不适合我。我做错了什么?

【问题讨论】:

  • 首先你想得到你没有在任何地方声明的地址,其次你必须在你的表单中声明一个方法,比如
  • 我建议你只了解 PHP 和 HTML 的基础知识。
  • 我确实声明了“地址”,当您单击提交按钮时,它将“地址”声明为 TRUE,并且函数运行良好。如果我在最后添加 ann echo,它会打印 - 但 $email 变量仍然为空。我尝试声明表单操作和方法,但没有区别。
  • @KristiánFilo 如果您介意将我的答案设为正确答案,因为我是第一个提出答案的人

标签: php forms post get


【解决方案1】:

您的表单中缺少 post 方法。

<form method="post" action="example.com/index.php?address=true">
     <input type="text" name="test" id="test" value="">
     <input type="submit" value="ODOSLAŤ" />
</form>

您还必须更改以下行。

if (isset($_GET['address'])) {

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

您想在触发 FreedomPride 提到的动作后发布

结论

如果您知道将来要发布该数据,您想声明例如 post method

正如 FreedomPride 也提到的:

您正在使用GET,但如果用户没有输入任何内容,您的脚本将无法运行,建议您使用POST

【讨论】:

    【解决方案2】:

    您没有提交表单。

    如下修改你的代码....

    <form method="post" action="example.com/index.php?address=true">
         <input type="text" name="test" id="test" value="">
         <input type="submit" value="ODOSLAŤ" />
    </form>
    

    你会得到你想要的......

    【讨论】:

      【解决方案3】:

      这就是汤姆提到的你所缺少的。

      <form method="post" action="yourphp.php">
      <input type="text" name="address" id="test" value="">
      <input type="submit" name="submit"/>
      </form>
      

      在你的 PHP 中,如果它被触发,它应该被发布

      if (isset($_POST['address'])) {
      
          $email = $_POST['test'];
      
          $myfile = fopen("log.txt","a") or die("Error.");
          fwrite($myfile, "\n".$email);
      
          // this prints nothing
          echo $email;  
        }
      

      解释:-

      在一个表单中,需要一个动作来将动作传递给下一个有动作的调用者。该操作可以为空或将其值传递给另一个脚本。

      在您的 PHP 中,您实际上使用的是 GET。如果用户没有输入任何内容怎么办。所以推荐使用POST

      【讨论】:

        猜你喜欢
        • 2021-08-31
        • 1970-01-01
        • 2013-08-09
        • 1970-01-01
        • 2015-02-15
        • 1970-01-01
        • 2020-05-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多