|
|||
|
|
|||
|
|
Handling checkbox in a PHP form processorThis tutorial will introduct HTML check boxes and how to deal with them in PHP. Single check boxLet's create a simple form with a single check box that indicates whether wheelchair access is needed or not.
<form action="checkbox-form.php" method="post">
In PHP, use the standard $_POST array to access the value, just as before. If $_POST['formWheelchair'] is "Yes", then the box was checked. If it's "", then the box was not checked. Here's an example of PHP handling the form:
<?php
That's all there is to it. You could make a whole group of checkboxes using this method, but there is a much easier way to do it with PHP. Check box groupThere are often situations where a group of related checkboxes are needed on a form. Let's build on the above example and give the user a list of buildings that he is requesting door access to.
<form action="checkbox-form.php" method="post">
Notice that all the building checkboxes have the exact same name. Also notice that each name ends in []. This is done on purpose. Using the same name indicates that these checkboxes are all related. Using [] indicates that the selected values will be accessed by PHP as an array. That is, $_POST['formDoor'] won't return a single string like it's been doing up until now; it will instead return an array consisting of all the values of the checkboxes that were checked. For instance, if I checked all the boxes, $_POST['formDoor'] would be an array consisting of: {A,B,C,D,E}. Here's an example of how to retrieve the array of values and display them:
<?php
If no checkboxes are checked, $_POST['formDoor'] will be "null", so use the "is_null" function to check for this case. If it's not null, then this example just loops through the array (using the "count" function to determine the size of the array) and prints out the building codes for the buildings that were checked. Usually this type of loop will be used to construct multiple SQL queries to insert the data. The "implode" PHP function can also be used to combine each element of the array into one string. Download the php form checkbox sample code.
Related pages
|
| Copyright © 2008 html-form-guide.com . All rights reserved. | ||||