⊗ppPmFmOFH 299 of 447 menu

Form Processing in a Single PHP File

In the previous lesson, our form was located on one page but submitted to another. Actually, this is not necessary. If you leave the action attribute empty or remove it altogether, the form will be submitted to this same page.

How it will work: on the first visit to the page, we will fill out the form and click the button. After that, the page will refresh and its code will execute again, but this time with the form data.

Let's look at an example. Suppose we have a form and its processing in one file:

<form action="" method="GET"> <input name="test1"> <input name="test2"> <input type="submit"> </form> <?php var_dump($_GET); ?>

On the first visit to the page, the var_dump function will output an empty array. And after submitting the form, it will output the form data. That is, the first time $_GET will be empty, and the second time - it will contain the form data.

This can lead to problems. Suppose, for example, we will enter numbers into the form and want to display the sum of these numbers on the screen:

<form action="" method="GET"> <input name="test1"> <input name="test2"> <input type="submit"> </form> <?php echo $_GET['test1'] + $_GET['test2']; ?>

In this case, on the first visit to the page, we will see PHP errors related to the fact that the $_GET array is empty, but we are accessing its elements.

It should be noted here that you might not see errors in the browser. In this case, check that PHP error reporting is enabled, and also make sure that this is your first visit to the page and there is no form data in the address bar.

Let's fix the problem. To do this, let's add a condition to check if the form was submitted.

For example, you can check if $_GET is not empty. If $_GET is not empty - then the form was submitted and you can perform the summation. Otherwise, we are still on the first visit to the page and the summation will not be performed. So, here is the corrected code:

<form action="" method="GET"> <input name="test1"> <input name="test2"> <input type="submit"> </form> <?php if (!empty($_GET)) { echo $_GET['test1'] + $_GET['test2']; } ?>

Ask the user for their last name, first name, and patronymic. After submitting the form, display the entered data on the screen.

byenru