【问题标题】:use $_GET['']; value inside $_POST[''] and submit it to the same page and display in the same page使用 $_GET['']; $_POST[''] 内的值并提交到同一页面并显示在同一页面中
【发布时间】:2019-05-16 19:51:48
【问题描述】:

我是 php 新手,在练习时遇到了一个问题。实际上,我有两个文件 index1.php 和 index2.php。在 index1.php 中,我有一个具有唯一 ID 的链接

<a href="index2.php?companyid=<?php echo $row('company_id');?>>details</a>

我在 index2.php 中得到了这个值

if(isset($_GET['companyid'])){
  $companyid = $_GET['companyid'];
 }

现在我在 index2.php 中有一个搜索表单

<form method="POST" action="index2.php">
  <input type="text" name="search">
  <button type="submit" name="submit">submit</button>
</form>

现在点击按钮我希望搜索结果显示在同一页面中

'index2.php?companyid=$companyid'

但是如果我尝试在同一页面中使用$_POST['submit'];,它会将我带到index2.php 而不是index2.php?companyid=$companyid,如果我不使用$_POST['submit'];echo $companyid; 它提供了价值并且工作正常。我想要的是使用$companyid' value inside ``$_POST['submit']; as 并在与以前相同的 url 中显示结果

if(isset($_POST['submit']){
  $companyid //throws an error index of company id
}

任何帮助将不胜感激

【问题讨论】:

  • 您没有在 POST 请求中传递公司 ID,因此在新页面加载时它不存在。 PHP 是无状态的。它不记得请求之间的任何内容。为了“记住”事物,您可以将它们作为查询字符串值传递,将它们作为 POST 请求中的请求主体参数发送,或者使用 cookie 作为存储机制。在您的情况下,您可能希望将公司 ID 作为 URL 查询字符串的一部分。

标签: php html mysql forms


【解决方案1】:

首先,您似乎没有在表单本身中使用公司 ID,因此它不会作为 POST 的一部分提交。您可能会使用:

<form method="POST" action="index2.php">
  <?php if (isset($companyid)): ?>
    <input type="hidden" name="companyid" value="<?= $companyid; ?>">
  <?php endif; ?>
  <input type="text" name="search">
  <button type="submit" name="submit">submit</button>
</form>

但您可能还需要将逻辑更改为:

if(isset($_POST['companyid'])){
  $companyid = $_POST['companyid'];
}else if(isset($_GET['companyid'])){
  $companyid = $_GET['companyid'];
}

【讨论】:

  • 您可以使用$_REQUEST 代替if 链来覆盖整个负载。
  • 是的,我考虑过,我只是认为这更好地突出了逻辑。 (但我完全同意...)
【解决方案2】:

正如 Josh 在 cmets 中指出的那样,PHP 无法记住您之前的 GET 请求,但这可以通过更改 form 元素的 action 属性轻松解决。通过这样做,您可以传递以前的数据。这看起来有点像这样:

<form method="POST" action="index2.php?companyid=<?php echo $companyid;?>">
    <input type="text" name="search">
    <button type="submit" name="submit">submit</button>
</form>

这样,您将被重定向到带有 URL 参数的 index2.php,并且您将能够使用 $_POST$_GET 检索 searchcompanyid 或同时使用 $_REQUEST

【讨论】:

  • 这有点帮助,但如果我尝试回显 $companyid,我仍然无法点击按钮使其变白。我已经完成了if(isset($_POST['submit'])){$id = $_GET['companyid']; echo $id;}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
相关资源
最近更新 更多