Well... here is something very simple, but hopefully will illustrate the point. It contains both the form and the code:
Save code as form.php
- Code: Select all
<?php
// Check if we just started counting
if (isset ($HTTP_POST_VARS['count']) && $HTTP_POST_VARS['count'] != '') {
$count = $HTTP_POST_VARS['count'];
} else {
$count = 0;
}
// Lets count (increment by one).
$count ++;
?>
<html>
<head></head>
<body>
<form action="form.php" method="post">
Learning to count: <input type="text" name="count" value="<?php echo $count; ?>"/>
<input type="submit" value="Count"/>
</form>
</body>
</html>
From an experienced coding perspective, this little snippet has alot of things wrong with it. It does work fine (yes, its tested). Learning to code in PHP is often an iterative process. You can worry about proper semantic coding and methodology as you gain experience.
Edit:
Here is a small explaination of some of the more important details. The top portion of the segment is a piece of code that intercepts the input from the form and does some work on it. In this case, we are taking data from the form field "count" and adding 1 to it. We then set this variable back into our form. The PHP global system variable HTTP_POST_VARS contains all the data that was sent to the web server in a form with the POST method. If you use the GET method, your variables are stored in HTTP_GET_VARS. PHP5 changed this a bit, but still uses these names for compatibility. You'll note that I verify that the post data has something in it before I do anything with it. This isn't as important in PHP, but validating input is always an important idea to start with early.
The form itself is pretty simple. The form tag has at least two basic elements. The "action" is the name of the script you are posting to. In this case, its ourself, "form.php". You can also provide a "method" of either GET or POST. Forms always default to GET, so if you leave out the method, you will not get any POST data in PHP. GET method will encode the form options into the URL itself, so you get something like this:
http://host.com/form.php?count=1
Alot of coders don't like exposing their variables this way. POST allows all that data to be encoded into the HTTP header that the browser sends to the server. Most users don't go looking for this info, but if you're serious about web development, the HTTP header can quickly become your friend. One other advantage of POST is that it has no real size limitation (other than what the server forces), so if you have large amounts of text to push around in forms, you have to use post. Otherwise, your data will get truncated or behave badly
Anyhow, hope this helps...