Skip to content
Advertisement

Access data in URL using GET and send it to database using POST

I am sending an id using the url. However, i can only access the $GET[‘id’] variable when the page loads. When I go on to submit the form, the variable is undefined. What could be the problem

   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);
            }
         
        }
    
    }

Advertisement

Answer

When you build the form, the target should include the GET parameter too. This is how GET parameters are passed around. $_POST will be populated with the form fields, $_GET will be populated with whatever is in the 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> 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement