Tuesday, 31 January 2017

$_POST IN PHP

It is same as $_GET nut it holds the data of post method

Program – To display the output in the same page i.e. to write both HTML and PHP script in one PHP.

form.php
<?php
$text1 = $_GET['t1'];
$text2 = $_GET['t2'];
echo "values is ".$text1;
echo "value is ".$text2;
?>

<form method="post" action="">
Text1<input type="text" name="t1"><br>
Text2<input type="text" name="t2"><br>
<input type="submit" name="Sub" value="Click">
</form>

Note – In the above program, the PHP script is first executed, since the form is not yet executed, the values are undefined for text1 and text2 variables. Thus to eliminate this problem, we rewrite the code as –

<?php
if(isset($_POST['Sub']))
{
          $text1 = $_POST['t1'];
          $text2 = $_POST['t2'];
          echo "values is ".$text1;
          echo "value is ".$text2;
}
?>

Program – To post the values in the textbox after reloading of form (maintain posted values).

<form method="post" action="">
Text1<input type="text" name="t1" value="<?php
                                                echo $_POST['t1'];?>"><br>
Text2<input type="text" name="t2" value="<?php
                                                echo $_POST['t2'];?>"><br>
<input type="submit" name="Sub" value="Click">
</form>

Note – ‘name’ property is compulsory. If more than one submit controls are there in the form, then only one control should pass to server. If there are 2 textbox + 2 submit button then total number of control passed at a time is 3.

Program – To perform addition and subtraction of two numbers.

<?php
if(isset($_POST['Sub']))
{
$text1 = $_POST['t1'];
$text2 = $_POST['t2'];
if($_POST['Sub']=="+")
{
$res=$text1+$text2;
echo $res;
}
else if($_POST['Sub']=="-")
{
$res=$text1-$text2;
echo $res;
}
}
?>

<form method="post" action="">
Text1<input type="text" name="t1"><br>
Text2<input type="text" name="t2"><br>
<input type="submit" name="Sub" value="+">
<input type="submit" name="Sub" value="-">
</form> 

No comments:

Post a Comment