PHP Form Handling

kane

194.***.***.***
2,072 days ago

PHP Form Handling

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Form example:

Code:

<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>

The example HTML page above contains two input fields and a submit button. When the user fills in this form and click on the submit button, the form data is sent to the "welcome.php" file. The "welcome.php" file looks like this:

Code:

<html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html>

A sample output of the above script may be:

Code:

Welcome Kane. You are 15 years old.

Form Validation User input should be validated on the browser whenever possible (by client scripts (JavaScript)). Browser validation is faster and you reduce the server load. You should consider using server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.

penguinmama

12.***.***.***
2,063 days ago
I would like more information on posting the form to itself! How does one access the "action" from the form with PHP?

Dismounted

59.***.***.***
2,061 days ago
Depending on the method (Post or Get), you retrive data by using;

PHP code:

$_POST['OBJECT_NAME'] // Post Method, Replace "object_name" with field name

OR

PHP code:

$_GET['OBJECT_NAME'] // Get Method, Replace "object_name" with field name

penguinmama

12.***.***.***
2,060 days ago
Right, I know that. However, there isn't a $_POST['action'] variable, that I know of... so how would you know what is being asked for in the next iteration of the script-run?