code_sniffer code_sniffer - 4 months ago 8
SQL Question

Is there a way to make a variable created within an isset($_GET[]) condition be accessed inside an isset($_POST[]) condition?

I have been stuck on this following problem for the past few days which I cannot seem to resolve.

I have the following two if statements within a PHP file:

This statement gets the post ID from the previous page.

if(isset($_GET['post'])){

$post_id = $_GET['post'];
}


This statement inserts user inputs into a DB_Table after a button is clicked. Amongst the data inserted into the DB_Table, I want the $post_id from the (isset($_GET['post'])) condition to be one of them.

if(isset($_POST['submit'])){

$insert_member = "insert into hcg_members (post_id, member_id) values ('$post_id','$match_member_id')";

$run_event = mysqli_query($con,$insert_member);
}


Only problem is, I can't seem to find a way to retain the $post_id's data. I have tried to set $post_id as a $Globals variable but this does not work.

As a way to find troubleshoot the problem I have successfully echoed $post_id from outside the if(isset($_GET[])) statement but the echo statement stops working once I try to run it from the if(isset($_POST[])) statement.

Any help would be appreciated, thanks in advance.

Answer

Okay, so just to clarify for those who found my question unclear. I was trying to make 2 different calls to my script.

  • The first one was a GET request.
  • The second one was a POST request.

I was trying to do the above while retaining the value of $post_id which was located in the GET request when using it in the POST request.

As advised by dan08 & Crayon Violent, variables' values cannot be retained when trying to pass them from one HTTP request method to another. As pointed out by Crayon Violent, http is a stateless protocol, which makes PHP unable to remember anything from the previous request.

I therefore used one of Crayon Violent's solution which was to use session in order to carry over the variable from the Get Request method to the POST Request method, and it worked! :)

There's the solution:

GET Request Method:

<?php 
    @session_start(); 
    if(isset($_GET['post'])){
        $post_id = $_GET['post'];
         $_SESSION['respite_id'] = $post_id;
    }   
         ...
         ...
?>

POST Request Method:

<?php 
    include("includes/database.php");

    if(isset($_POST['submit'])){

     $respite_id = $_SESSION['respite_id'];

     $insert_member = "insert into hcg_members (post_id, member_id) values ('$post_id','$match_member_id')";
     $run_event = mysqli_query($con,$insert_member);            
        ...
        ...

    }
?>

Thanks again to dan08 and Crayon Violent's support! :)