Note the use of $PHP_SELF again. Like I said in Lesson 1, you can use PHP anywhere inside your HTML code. You'll also notice that each form element matches the field name in the database. This is not compulsory; it's just a good idea so you can get your head around your code later on.
Also notice that I've given the Submit button a name attribute. I've done this so I can test for the existence of a $submit variable. That way, when the page is called again, I'll know whether someone used this form.
I should mention that you don't have to have a page that loops back on itself. You can span two, three, or more pages, if you like. This way everything stays compact.
OK, let's add some code that will check for the form input. Just to prove that the form input does make it through, I'll dump all the variables to the screen with $HTTP_POST_VARS. This is a useful debugging feature. If you ever need to see all the variables on a page, use $GLOBALS.
<html>
<body>
<?php
if ($submit) {
// process form
while (list($name, $value) = each($HTTP_POST_VARS)) {
echo "$name = $value<br>\n";
}
} else{
// display form
?>
<form method="post" action="<?php echo $PHP_SELF?>">
First name:<input type="Text" name="first"><br>
Last name:<input type="Text" name="last"><br>
Address:<input type="Text" name="address"><br>
Position:<input type="Text" name="position"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
} // end if
?>
</body>
</html>
Now that this is looking good, let's take the form information and post it to the database.
<html>
<body>
<?php
if ($submit) {
// process form
$db = mysql_connect("localhost", "root");
mysql_select_db("mydb",$db);
$sql = "INSERT INTO employees (first,last,address,position) VALUES ('$first','$last','$address','$position')";
$result = mysql_query($sql);
echo "Thank you! Information entered.\n";
} else{
// display form
?>
<form method="post" action="<?php echo $PHP_SELF?>">
First name:<input type="Text" name="first"><br>
Last name:<input type="Text" name="last"><br>
Address:<input type="Text" name="address"><br>
Position:<input type="Text" name="position"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
} // end if
?>
</body>
</html>
You've now inserted data into the database. It's still far from perfect. What if someone leaves a field blank or enters text when we want a numeric entry? What if there's an error somewhere?