Website Database Basics With PHP and MySQL - Checkboxes and other HTML form processing (
Page 6 of 6 )
HTML forms are
easy to design, as long as you allow one value per field. When you allow more
than one value, the processing gets tricky.
Checkboxes
SELECT multiple scrolling lists
Searching with multiple values
Checkboxes
Checkboxes are the simplest way to allow users to enter more
than one value into a field:
What pets do you have?
You can check one, two, or
all of the pets. The HTML code looks like this:
What pets do you have?
<FORM>
<INPUT TYPE=checkbox NAME=PET_ARRAY[] value=dog> Dog<br>
<INPUT TYPE=checkbox NAME=PET_ARRAY[] value=cat> Cat<br>
<INPUT TYPE=checkbox NAME=PET_ARRAY[] value=fish> Fish<br>
</FORM>
The MySQL field name is PET, but here we
use PET_ARRAY[]. When the user clicks the SUBMIT
button, the values are passed to the header looking like this:
5B is 91 in hexadecimal, and the HTML
character entity for left square bracket — [ — is [, so
%5B means left square bracket. 5D is 93 in
hexadecimal, and the HTML character entity for right square bracket —
] — is ], so %5D means right square bracket.
When we get to the PHP script that processes this form, we use this script to
put both values into one field. The PET field is a SET
datatype.
if ($PET_ARRAY)
{
$PET = implode($PET_ARRAY, ",");
$result = mysql_query ("UPDATE dbname
SET PET = '$PET'
");
if(!$result)
{
echo "<B>UPDATE unsuccessful:</b> ", mysql_error();
exit;
}
}
if ($PET_ARRAY) checks if the user
checked any of the boxes. If the user doesn't have any pets, the field is left
empty.
$PET = implode($PET_ARRAY, ","); converts the array into a
string, with the elements separated by commas. The values passed to the header
above would come out as
dog,cat
The query then puts the string into the
PET of the database.
To search a SET datatype, remember to put %
wildcards before and after the search value. This is necessary to find one of
several values, and ignore the commas. E.g.,