Naming Your HTML Form Fields with an Associative Array
When using database entries to dynamically build HTML forms, how do you go about naming the form fields? Do you name them "Field1", "Field2′, etc.? Or do you have a more efficient way to access the fields when processing the form submissions? If you haven't tried using an array as the name, you may be missing out.
Let's say we're developing a survey which asks whether someone has watched certain movies. The movie information is in a database like the following:
id | title | year_released |
---|---|---|
6 | Matrix | 1999 |
7 | Star Wars: A New Hope | 1977 |
8 | Garbage Pail Kids Movie | 1987 |
When processing submissions, we need to know which movie they are answering yes or no to. With a database, the movie's ID can be passed along with each response. One way to add the ID is to include it in the form field's name.
<div>Matrix (1999) <input type='radio' name='movie6' id='movie6_Yes' value='Yes' /> <label for='movie6_Yes'>Yes</label> <input type='radio' name='movie6' id='movie6_No' value='No' /> <label for='movie6_No'>No</label></div>
However, this might be more of a hassle than it's worth. Once the form has been submitted, we need to access those responses and verify that they contain a "Yes" or "No" value. We could loop through the $_POST array looking for anything named "movie" and followed by a number. We could also utilize the movie database to get all the $_POST variables similar to how the form was built. Or… the names for our radio buttons could be renamed as an array (HTML Input Forms – Sending in an array in PHP).
<div>Matrix (1999) <input type='radio' name='movie[6]' id='movie6_Yes' value='Yes' /> <label for='movie6_Yes'>Yes</label> <input type='radio' name='movie[6]' id='movie6_No' value='No' /> <label for='movie6_No'>No</label></div>
Now the responses are grouped into array called "movie". They can be processed with a simple foreach loop.
foreach($_POST['movie'] as $key=>$value) {
print "<div>Movie ID: $key | Seen the movie? $value</div>";
}
0 Comments
There are currently no comments.
Leave a Comment