Good tips everybody, thanks! A brief summary:
SERVER-SIDE PROCESSING (GET and POST)
<!-- If your form submission WILL NOT WRITE anything on the SERVER-SIDE, use GET -->
<form action="action.php" method="get">
<!-- If your form submission WILL WRITE some data on the SERVER-SIDE, use POST -->
<form action="action.php" method="post">
CLIENT-SIDE PROCESSING (ID and NAME)
<!-- If the CLIENT-SIDE NEEDS to access or modify this field, use the id attribute -->
<input id="firstName" name="firstName" type="text">
<!-- create a script that runs on the CLIENT-SIDE to access and modify the field -->
<script type="javascript">
var firstName = document.getElementById("firstName");
firstName.value = 'some text';
firstName.focus();
</script>
<!-- If the CLIENT-SIDE DOES NOT NEED to access or modify this field, -->
<!-- then there is no need for the ID attribute or a client side script -->
<input name="firstName" type="text">
Note the HTML SYNTAX:
- In <form>, 'get' and 'post' are the VALUE of the attribute named 'method'.
- In <input>, 'id' and 'name' are the NAME of the attribute with values of 'firstName'.
Uso de Formularios HTML
Otra de las características de PHP es que gestiona formularios de HTML. El concepto básico que es importante entender es que cualquier elemento de los formularios estará disponible automáticamente en su código PHP. Por favor refiérase a la sección titulada Variables fuera de PHP en el manual para más información y ejemplos sobre cómo usar formularios HTML con PHP. Observemos un ejemplo:
Example #1 Un formulario HTML sencillo
<form action="accion.php" method="POST"> Su nombre: <input type="text" name="nombre" /> Su edad: <input type="text" name="edad" /> <input type="submit"> </form>
No hay nada especial en este formularo, es HTML limpio sin ninguna clase de etiquetas desconocidas. Cuando el cliente llena éste formulario y oprime el botón etiquetado "Submit", una página titulada accion.php es llamada. En este archivo encontrará algo así:
Example #2 Procesamiento de información de nuestro formulario HTML
Hola <?php echo $_POST["nombre"]; ?>.
Tiene <?php echo $_POST["edad"]; ?> años
Un ejemplo del resultado de este script podría ser:
Hola José.
Tiene 22 años
Es aparentemente obvio lo que hace. No hay mucho más que decir al respecto. Las variables $_POST["nombre"] y $_POST["edad"] son definidas automáticamente por PHP. Hace un momento usamos la variable autoglobal $_SERVER, ahora hemos introducido autoglobal $_POST, que contiene toda la información enviada por el método POST. Fíjese en el atributo method en nuestro formulario; es POST. Si hubiéramos usado GET, entonces nuestra información estaría en la variable autoglobal $_GET. También puede utilizar la autoglobal $_REQUEST si no le importa el origen de la petición. Ésta variable contiene una mezcla de información GET, POST y COOKIE. También puede ver la función import_request_variables().
Uso de Formularios HTML
05-Oct-2008 12:03
10-Aug-2008 05:55
@Lord Pacal: the attributes 'name' and 'id' have different intent and are used differently. 'id' uniquely identifies an element in the HTML DOM, whereas 'name' identifies the field that will be transmitted on the form submit. You can omit the 'id' attribute, but not the 'name' attribute.
Where a field requires multiple elements, e.g. radio buttons and check boxes, the 'name' attribute must be the same but the 'id' must be unique for each element.
'id' is useful for linking explicitly to the element, as in the following cases:
* CSS selector by ID
* JavaScript code, e.g. in-browser form validation or active forms
* the target of a <label> element
The last example is one not used nearly enough, as it allows the user to click on the text next to a radio button or check box - a bigger target and thus easier for users not used to using a mouse:
<input type="checkbox" name="example" value="yes" id="example_yes"/>
<label for="example_yes">Yes, I can click on the text and check the box</label>
29-Mar-2008 10:27
I was so shocked that some servers have a problem regarding the Submit Type Name and gives a "Not Acceptable error" or Error 406.
Consider the example below :
<form action="blah.php" method="POST">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="Submit_btn" id="Submit_btn" value="Send">
</td>
</tr>
</table>
</form>
This very simple code triggers the "Not Acceptable Error" on
PHP Version 5.2.5 and Apache 1.3.41 (Unix) Server.
However to fix this below is the right code:
<form action="blah.php" method="POST">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="Submitbtn" id="Submit_btn" value="Send">
</td>
</tr>
</table>
</form>
The only problem that took me hours to find out is the "_" in the Submit Button.
Hope this help!
03-Jan-2008 06:38
One thing that tripped me up when I was first learning PHP was the use of the NAME attribute in form fields. The current convention is to use the ID attribute instead when creating forms. (Many HTML editors automatically include an ID attribute without a NAME attribute.) Now, I include both the NAME and ID attributes (with the same value) in all my form fields.
For example...
<form method="post">
<input type="text" id="field1">
<input type="submit" value="go">
</form>
If you then have a PHP page requesting the contents of the "field1" field...
<?php echo $_POST["field1"] ?>
...the above form will always return an empty string for "field1".
The solution is to include the NAME attribute...
<form method="post">
<input type="text" id="field1" name="field1">
<input type="submit" value="go">
</form>
With this change, the PHP code will correctly retrieve the value of the "field1" field.
08-Nov-2006 08:02
As Seth mentions, when a user clicks reload or goes back with the browser button, data sent to the server, may be sent again (after a click on the ok button).
It might be wise, to let the server handle whatever there is to handle, and then redirect (a redirect is not visible in the history and thus not reachable via reload or "back".
It cannot be used in this exact example, but as Seth also mentions, this example should be using GET instead of POST
05-May-2005 12:18
[Editor's Note: Since "." is not legal variable name PHP will translate the dot to underscore, i.e. "name.x" will become "name_x"]
Be careful, when using and processing forms which contains
<input type="image">
tag. Do not use in your scripts this elements attributes `name` and `value`, because MSIE and Opera do not send them to server.
Both are sending `name.x` and `name.y` coordiante variables to a server, so better use them.
01-Dec-2003 12:55
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.
You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.
