How to fetch data from HTML to PHP using Single file

Introduction

In my last article I will explained how we can fetch data from html to php in separate files. In this article I am going to explain how we can fetch data from html in the same file.

Let's take the same example where we have to take two numbers from the users. Create php file and add html code to create user interface.

Now I want when I click on submit button then my php code will start execution. So we have to use isset function to check whether form has been submitted or not.

sum.php

We will add code in the following manner:-


<?php

if(isset($_GET['b1']))
{
$num1=$_GET['t1'];
$num2=$_GET['t2'];
$sum=$num1+$num2;

echo "The sum of $num1 and $num2 is $sum";
}

?>

<html>
<head>

</head>

<body>
<form action="sum.php" method="get">
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>

		
		

Now execute this code and you will get following output:-

fetch data from html to php using single file

		Figure 1
		

HTML form to php output

		Figure 2
		
		

In this way we can fetch data from html controls in php.