PHP form tutorial Phase2

In the next step we will process the submitted data.




Step 2 - PHP form processing
________________________________________
PHP form tutorial

Now we have a HTML page with a form but if we press the submit button then we will get a Not Found message if the form.php file doesn't exists yet.
First you should save the HTML site shown in the previous step as form.php. Yes it is correct, we will create a compact PHP page which will display the HTML form and process it as well. But how it is possible? It is not so complicated. We will create a code which will display the HTML form if the user visit it. If the form is submitted then the code will recognize it and instead of displaying the form we will process the submitted data.
If a form was submitted and the script defined in the action parameter of the form tag is called then a so called super global array will be populated with the user entered information. In our example we have 4 inputs: 2 input text fields, 1 textarea and 1 input submit button. Each of them has its own name. As we defined to send form data as POST (See the method form parameter) so to $_POST array will contain 4 elements. Something like that:
Code:
1. $_POST['name'] : "John"
2. $_POST['email'] : "john@john.com"
3. $_POST['mesg'] : "Hello, my nam is John!"
4. $_POST['submitForm'] : "Send"
PHP F1
What does it mean? It means that we can check this array. If it is filled then the user has submitted the form and if it is empty then no submission was done so we need to display the form.
However it can happen that the visitor submitted an empty form by just clicking on the Send button. In this case only one of the above mentioned array element exists and it is the submitForm. In case of submitting a HTML form the submit button value always be present in the $_POST array. Now we can create a simple conditional statement to decide what to do. If the $_POST['submitForm'] doesn't exist then we display the form else print out a message that the form was submitted. The code to do this looks like this:
Code:
1.
4.

5.
6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. PHP F1 Ok, it's nice but what to do now. The visitor can submit an empty form? Yes, so now we need to extend our code with some input data validation as you can see on the next page.
Name:
Email:
Message:
 

0 comments:

Post a Comment