In this example I am going to explain how we can fetch values from our html controls in PHP file.
Suppose I have following screen
create html file and save it in c->wamp->www folder.
Now add following HTML code to create this form.
<!doctype html> <html lang="en"> <head> <title>HTML Form<> <meta charset="utf-8"> </head> <body> <form action="sum.php" method="post"> Enter first number:-<input type="text" name="t1"/> </br> Enter Second number:-<input type="text" name="t2"/> <br/> <input type="submit" value="Sum" name="b1"/> </form> </body> </html>
As you can see that I have add form tag and in form tag I have added sum.php.
This is my php file where I will fetch data of these controls. When I will click on sum button which is of submit type and it will redirect me to sum.php which is set in action.
You can also see that I have set the method as post. This is my http request method. We have two http method get and post.
Now create php file with the name of sum and fetch values of controls. We have two associative arrays for fetching these controls values.
If we are using get request then we will use $_GET array and if request is set as post then we will use $_POST array. We will use controls name as key in these array. As we know that we set name to each controls so we can pass these name as key to these two associative array to fetch the values.
<?php $num1=$_POST['t1']; $num2=$_POST['t2']; $sum=$num1+$num2; echo "The sum of $num1 and $num2 is $sum"; ?>
Now execute the code. First execute the html file and fill data and click on sum button and you will get following output:-
Now fetch the data from Get request. First you have to change the method in form tag. Set it as get. And then change sum.php file in the following manner:-
<?php $num1=$_GET['t1']; $num2=$_GET['t2']; $sum=$num1+$num2; echo "The sum of $num1 and $num2 is $sum"; ?>
Now execute the method and you will get following output:-
As you can see that when I used get request our data is binded on our URL which is not secured.
In this way we can fetch data from html to php.