【问题标题】:Access data in URL using GET and send it to database using POST使用 GET 访问 URL 中的数据并使用 POST 将其发送到数据库
【发布时间】:2020-09-28 22:42:49
【问题描述】:

我正在使用 url 发送一个 id。但是,我只能在页面加载时访问 $GET['id'] 变量。当我继续提交表单时,变量未定义。可能是什么问题

   if(isset($_GET['id'])) {
        $tripId = htmlspecialchars($_GET['id']);
    }
    
    
    if (isset($_POST['submit'])) {
   
    
        for($i = 0; $i < count($_POST['package']); $i++) {
    
    
            //check if there are any errors before proceeding
            if(array_filter($errors)) {
                print_r($errors);
            } else {
                $package = mysqli_real_escape_string($con, $_POST['package'][$i]);
                $price = mysqli_real_escape_string($con, $_POST['price'][$i]);
                $sql = "INSERT INTO packages(tripId,packageName,packagePrice) VALUES('$tripId','$package','$price')";
            }
    
            //check and redirect 
            if(mysqli_query($con, $sql)) {
                header('location: admin_home.php');
            } else {
                echo 'error' . mysqli_error($con);
            }
         
        }
    
    }

【问题讨论】:

  • 那么提供给action表单的URL可能不会传递GET变量。
  • 如果您使用 POST 提交表单,则不会填充 $_GET 数组
  • 是否可以获取 'id' 变量并将其持久化到 post 请求中?
  • @Mitya 确实如此,我可以在页面加载后立即访问变量,但是当我提交表单时,它是未定义的
  • @AlexGoonerArteta 是的,如果你 a) 将它放在表单的“action”方法中的 URL 中,或者 b) 将它放在表单中的隐藏字段中(但你会有在那种情况下通过 $_POST 在 PHP 中访问它)。不管怎样,这意味着它会在发送 POST 请求时再次提交

标签: php html forms http


【解决方案1】:

当您构建表单时,目标也应该包含 GET 参数。这就是 GET 参数的传递方式。 $_POST 将填充表单字段,$_GET 将填充 URL 中的任何内容。

<?php 

$url = '/process.php?' . http_build_query(['id' => $yourIdHere]);

?>

<form action="<?=$url;?>" method="POST">
  <label for="package">Package:</label>
  <input type="text" id="package" name="package"><br><br>
  <label for="price">Price:</label>
  <input type="text" id="price" name="price"><br><br>
  <input type="submit" value="Submit" name="submit">
</form> 

【讨论】:

  • 为了清楚起见,最好说表单的操作,而不是它的目标(这是一个不同的属性,虽然我知道你的意思。)
  • @Mitya 是的,对不起。那将是理想的。当我教人时,我只是发现学生将其描述为目标的混淆较少。虽然我通常会说“动作参数中的目标”,但我想我今晚有点懒了。
猜你喜欢
  • 2017-07-15
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 2020-09-25
  • 2016-05-09
相关资源
最近更新 更多