Access texbox values using POST method in PHP

10:16 AM 1 Comments

Things you need to know first.

POST method:

There are two method to request or submit data from specific resources (GET and POST). Here I'm going to discuss about POST method with a pretty simple example.

In order to use POST method to submit data, the value of the method attribute must be POST in the FORM tag.

<FORM method = "POST">
</FORM>

POST method submits the data to the same php file or another php file. It depends on the action attribute of your form tag.


<FORM method = "POST" action= "file2.php">
</FORM>

Leaving the action attribute null will submit the data to the same php file. Like, 

<FORM method = "POST" action= "">
</FORM>

Input Box

Input box must have the proper attributes. The important attribute needed for post method is "name". Each input box should have an unique name.

For example:

<input type = "text" name = "input_value1">
<input type = "text" name = "input_value2">
<input type = "text" name = "input_value3">
<input type = "text" name = "input_value4">
<input type = "submit" name = "submit_data">

Access value from the form 

When the data are submitted from the form, data are ready to get accessed in the target file. To check whether the request method is POST. 

if($_SERVER['REQUEST_METHOD'] == "POST)

(or)

if($_POST)

Assign all the variables inside this if condition, to prevent the "undefined variable" error.

To store the values of the text box to PHP variables,

$variable_name = $_POST['name_of_inputbox'];

Eg) $name = $_POST['input_name'];
       $email = $_POST['input_email'];

You can display the data by using 'echo'
 echo $name;
You can directly display the values without storing in variables also, but it's time consuming and leads to lengthy codes.
echo $_POST['input_name'];

Note: $_POST is a pre-defined associative array variable. When we submit the form, the form data are stored in this array with respective index names.

Example Program:


<form method="POST" action="">
<input type="text" name="input_name" placeholder="Name"></br>
<input type="text" name="input_username" placeholder="Username"></br>
<input type="text" name="input_email" placeholder="Email"></br>
<input type="password" name="input_password" placeholder="Password"></br>
<input type="submit" name="submit_data" value="Submit">
</form>
<?php 
if($_SERVER['REQUEST_METHOD'] == "POST"){
//storing variables
$name = $_POST['input_name'];
$username = $_POST['input_username'];
$email = $_POST['input_email'];
$pass = $_POST['input_password'];

//Display the values
echo $name."<br>";
echo $username."<br>";
echo $email."<br>";
echo $pass."<br>";

}
?>
Values are stored in the variables now, now go ahead and store it in your database table. Click here to learn how to store data in MySQL database . Cheers!

Jefinson O

I'm a PHP developer, I'm so interested to share something with people what I learn today. Blogging is my Hobby and I love doing it. Google

1 comment: