Populating checkboxes and select lists from an array

Populating checkboxes and select lists from an array

When you use checkboxes in a form, usually you want to save more than one choice.
You must indicate to PHP that you are submitting more than one piece of data with []

<INPUT TYPE="checkbox" NAME="temperature[]" VALUE="hot">Hot
<INPUT TYPE="checkbox" NAME="temperature[]" VALUE="cold">Cold

After submitting your form, save the array data into database.
You can use the implode function joins array elements into a string, then save that string to the
database.

PHP Code

if ($temperature){ $temps = implode(",", $temperature); }
 
$query= mysql_query("UPDATE table SET temperature='$temps'");

Pulling the info back out:
- connect to database and select some info
- if you had submitted temperature information as an array
- explode function splits a string by a character and produces an array

PHP Code

$temps=explode(",",$myrow["temperature"]);

When populating/printing your form with the values in your database, check to see which values were submitted as part of the temperature array, and populate the checkbox with them

PHP Code

<INPUT TYPE="checkbox" NAME="temperature[]" VALUE="hot"
<? for ($index=0; $index< count($temps); $index++){
if ($temps[$index]=="hot") { print(" CHECKED");}} ?>>Hot
 
<INPUT TYPE="checkbox" NAME="temperature[]" VALUE="cold"
<? for ($index=0; $index< count($temps); $index++){
if ($temps[$index]=="cold") { print(" CHECKED");}} ?>>Cold

A select list is very similar:

PHP Code

<select name="colors[]">
<option value="green"
<?
for ($index=0; $index< count($colors); $index++){
if ($colors[$index]=="green") { print(" SELECTED");} }
?> >green</option>
...
</select>
<php>
 
If you did not submit your checkbox/radio button values as an array then
the code to checkbox/radio button would look like:
 
PHP Code
<php>
<INPUT TYPE="checkbox" NAME="temperature" VALUE="hot"
<? if ($temp=="hot") { print(" CHECKED");} ?<<Hot
 
<INPUT TYPE="checkbox" NAME="temperature" VALUE="cold"
<? if ($temp=="cold") { print(" CHECKED");} ?<<Cold

A select list:

PHP Code

<SELECT NAME="month">
<option value="January" <? if ($month=="January") { print(" SELECTED");} ?>>January
<option value="February" <? if ($month=="February") { print(" SELECTED");} ?>>February
<option value="March" <? if ($month=="March") { print(" SELECTED");} ?>>March
<option value="April" <? if ($month=="April") { print(" SELECTED");} ?>>April
....
</SELECT>

Example:

PHP Code:

<?php
 
$x = ($w < 25) ? 'something' : 'somethingelse';
printValue(($size < 10) ? 'small' : 'big');
 
?>