使用$ _POST在同一页面上获取输入值

Pic*_*olo 5 php

对不起,如果这是一个相当基本的问题.

我有一个HTML表单的页面.代码如下所示:

<form action="submit.php" method="post">
  Example value: <input name="example" type="text" />
  Example value 2: <input name="example2" type="text" />
  <input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

然后在我的文件中submit.php,我有以下内容:

<?php
  $example = $_POST['example'];
  $example2 = $_POST['example2'];
  echo $example . " " . $example2;
?>
Run Code Online (Sandbox Code Playgroud)

但是,我想消除外部文件的使用.我想在同一页面上使用$ _POST变量.我该怎么做?

Kae*_*uCT 14

把它放在一个php文件上:

<?php
  if (isset($_POST['submit'])) {
    $example = $_POST['example'];
    $example2 = $_POST['example2'];
    echo $example . " " . $example2;
  }
?>
<form action="" method="post">
  Example value: <input name="example" type="text" />
  Example value 2: <input name="example2" type="text" />
  <input name="submit" type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

它将以PHP的形式执行整个文件.第一次打开它时,$_POST['submit']将不会设置,因为表单尚未发送.单击提交按钮后,它将打印信息.

  • @thordarson 感谢您的提醒!然而,我总是更愿意把它说得更明确。我认为 $_SERVER['PHP_SELF'] 对于这个例子会更好。 (2认同)