How to use $_POST[] to read inputs from a FORM
TAGS: PHP, POST


In this posting we will learn how to read inputs from a FORM on a webpage.
You can use the $_POST[''] to read all kinds of values from FORMS, f.eks; text, password, hidden, checkbox, radio, select, submit. As the name say it reads POSTs from FORMs where the METHOD is set to 'POST'. You can read the returned value in to a variable easily, just make something like this;

$myvar = $_POST['myfield']; 


You have then put the value of 'myfield', submitted from your FORM, in your variable $myvar, and you can use it in your code elsewhere.

The following code simply show a webpage with two textfields and a submitbutton. You can enter some names in the textfields and on submit you will see that the values are read from the form and send to the screen. This just shows how to read values from a form into variables. You can change and use it as you want, for example for entering names into our test database for our contacts.

<?php 

if (isset($_POST['readme']))  { 
showme(); 
} 

function showme() { 
$Firstname = $_POST['firstname']; 
$Lastname = $_POST['lastname']; 

echo "Your contact is: " . $Firstname . " " . $Lastname; 
//exit(); 
} 

echo "<HTML> 
<BODY> 
<FORM METHOD='POST' ACTION=''> 
<TABLE> 

<TR> 
<TD>Firstname: </TD> 
<TD><INPUT TYPE='text' NAME='firstname' VALUE='" . $Firstname . "'> 
</TD> 
</TR> 

<TR> 
<TD>Lastname: </TD> 
<TD><INPUT TYPE='text' NAME='lastname' VALUE='" . $Lastname . "'> 
</TD> 
</TR> 

<TR> 
<TD></TD> 
<TD><INPUT TYPE='submit' NAME='readme' VALUE='Okay, read me'> 

</TR> 
</TABLE> 
</FORM> 
</BODY> 
</HTML>"; 
?> 


In the next post I will use this example and show you how IF works in PHP.