使用$get[“”];在$\u post['']内赋值,并将其提交到同一页并显示在同一页中

wsewodh2  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(281)

我是新来的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 它也会抛出错误 undefined index of $companyid 如果我不使用 $_POST['submit']; 以及 echo $companyid; 它很有价值,也很好用。我只想用它 $companyid' value inside ``$_POST['submit']; 和以前一样,在相同的url中显示结果

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

任何帮助都将不胜感激

zz2j4svz

zz2j4svz1#

首先,看起来您没有在表单本身中使用公司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'];
}
mm5n2pyu

mm5n2pyu2#

正如josh在评论中指出的那样,php无法记住以前的代码 GET 但通过改变 action 的属性 form 元素。通过这样做,您可以传递以前的数据。这看起来有点像这样:

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

这样您将被重定向到 index2.php 如果url参数存在,您将能够检索这两个参数 search 以及 companyid 使用 $_POST 以及 $_GET 或使用 $_REQUEST 两个都是。

相关问题