Home
   About Me
   Rene's Resume
   Presentations
   Services
   Rates & Contracts
   Portfolio / Clients
   Demo Apps
   White Papers & Tips
   Tutorials
   Contact Me
 

Form variables in PHP

Now that you know how to get the data out of the database, it also helps to know how to stuff it back in again. Most of the users you're writing these database applications for don't know how to write SQL inserts on their own, and/or you don't want to give them full access to your database.

The easiest way around these problems is to create an HTML form which asks them nicely for the information you want. When the form is submitted, a PHP script will read the information and stuff the results into the database. When PHP is called as the action to a form, all of the form variables are put into global arrays. i.e. If your HTML form says:

    <form action="myscript.php" method="GET">
    <input type=text name=Name size=20>
    <input type=submit value="Submit Form">
    <form>
    

4.1 $_GET and $_POST

The PHP script can reference the form value via $_GET['Name']. Use $_POST['Name'] if your form method is POST. For example:

    echo("The name you entered was: $_GET['Name']\n");

4.2 Forms and Arrays

Sometimes HTML forms need to handle arrays. The two most common situations are checkboxes and multiple selects. In these cases, it's possible to get multiple values for the same variable name, in which case PHP makes an array out of them. For example, using this HTML form:

    <form action="pet_survey.php" method="post">
    <p>What kind of Pets do you have?
    <input type=checkbox name=Pets value="Dog"> Dog
    <input type=checkbox name=Pets value="Cat"> Cat
    <input type=checkbox name=Pets value="Fish"> Fish
    <input type=checkbox name=Pets value="Ferret"> Ferret
    <input type=submit value="Submit">
    </form>
    

The user can check off none, one, two, three or all four of the checkboxes prior to submitting the form. A good method of looking over the data might be:

    foreach ($_POST['Pets] as $animal) {
    	print("<p>You have at least one \$animal.\n");
    }
    

The problem case occurs when the user only selects one value out of all their choices. In this case, PHP only creates a scalar value, which breaks the foreach statement above. In order to force PHP to create an array even when there is only one value, include square brackets after the variable name in the HTML form. For example:

    <form action="pet_survey.php" method="post">
    <p>What kind of Pets do you have?
    <input type=checkbox name=Pets[] value="Dog"> Dog
    <input type=checkbox name=Pets[] value="Cat"> Cat
    <input type=checkbox name=Pets[] value="Fish"> Fish
    <input type=checkbox name=Pets[] value="Ferret"> Ferret
    <input type=submit value="Submit">
    </form>
    

 

This page was generated in 0.0011 seconds.
Website content © 2024