My lessons are now into their second week and we’ve still got a way to go yet. This week we will be looking into IF and WHILE statements, $_GET, $_POST and we’ll also look into arrays near the end of the week.
Yesterday we did a simple lesson on $_GET and how to get values from a URL. Today another simple lesson on $_POST and the confusion that comes with it. I introduced you to $_POST in last Friday’s big special and today we are going into much more detail.
Lesson 8: $_POST and Forms
As I showed in Friday’s round up, we use $_POST to collect the values of submitted form data. Some confusion that I had for a while was whether or not to use the name or id attribute in the form fields to let $_POST work. I’ll settle this now – for $_POST to collect the data from the form fields, you need to assign a name attribute to them. The id can be used for labels, CSS classes and other things. Here’s a sample form form.php:
<form action="process.php" method="post">
First Name: <input type="text" name="fname" size="25" />
Last Name: <input type="text" name="lname" size="25" />
Over 16? <input type="radio" name="age" value="1" /> Yes <input type="radio" name="age" value="0" /> No
<input type="submit" value="submit form" />
</form>
In the above form we would get 3 values returned through $_POST. These would be the first name, last name and over 16 values. Here’s how we’d capture these values. This file would be process.php, as determined in the form’s first line:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age']; //either 1 or 0
$name = $fname." ".$lname; //stitch the first and last names together
?>
Pretty simple to get the form fields’ values. On Friday we are going to combine everything and a lot of form fields to create a signup form which will include this, arrays and a bit of validation.