Code_Ed_Student
Code_Ed_Student

Reputation: 1190

Passing form values from one page to another

In my form I am trying to pass acad_id to academy_view.php page. After the form submits I am trying to append acad_id to the url. In this way I can use GET in academy_view.php to pull up the records from mysql db. But everytime after submission the post url has an empty field for id.

academy_create.php

$acad_id = $_POST['acad_id'];
<form action="academy_view.php?id=<?php echo $acad_id; ?>" method="POST">
        Name: <input type="text" name="name"></br>
        Academy ID: <input type="text" id="acad_id" name="acad_id"></br>
<input value="SAVE" name="submit" type="submit">
</form> 

academy_view.php

if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0){
                 // query db
            $acad_id = $_GET['id'];

//Some Code

}

After submitting the URL shows id empty: http://www.example.com/academy_view.php?id=

Upvotes: 1

Views: 18519

Answers (2)

erny
erny

Reputation: 2489

The way to transport values (state) from one page to another is through request parameters, e.g.:

  • URL, like GET parameters
  • Request body, like form POSTs.

Suppose you are in academy_create.php and have already the request parameter (GET or POST) acad_id, i.e. URL = 'http://example.com/academy_create.php?acad_id=1' or as form field, you could do the following if don't want the user to fill out "acad_id" (it's already determined):

...
$acad_id = $_REQUEST['acad_id'];
...    
<form action="academy_view.php" method="POST">
  Name: <input type="text" name="name"></br>
  Academy ID: <input type="hidden" id="acad_id" name="acad_id" value="$acad_id"></br>
<input value="SAVE" name="submit" type="submit">
</form> 

If you want the value to be changeable by the user, just change "hidden" to "text".

If you want the value to be readonly, set add the readonly to the input.

Now, in academy_view.php you can get the value again with:

$acad_id = $_REQUEST['acad_id'];

Upvotes: 0

rjv
rjv

Reputation: 6766

You can edit you code to use POST as follows

<form action="academy_view.php" method="POST">
    Name: <input type="text" name="name"></br>
    Academy ID: <input type="text" id="acad_id" name="id"></br>
<input value="SAVE" name="submit" type="submit">
</form> 

And

if (isset($_POST['id']) && is_numeric($_POST['id']) && $_POST['id'] > 0){
             // query db
        $acad_id = $_POST['id'];

//Some Code

}

Upvotes: 2

Related Questions