Retrieving and Populating Checkboxes from MySQL

I currently have a form that inserts the data into a MySQL db. I also have a form that will allow users to update their information. I am having trouble retrieving and populating the checkboxes from the database.

I have 3 checkboxes: Energy, Economy, and Housing

Information is stored in the db field “Interests”

How can I get the fields to show checked if they had previously checked the information and also the ability to update their selections.

Thanks!

Assuming the data from the database is made available into variables (e.g. $economy) and these variables have true/false states …

<input type="checkbox" name="economy" value="yes" <?php if ($economy) echo 'checked="checked"' ?> >

… will pre-check the checkbox if true.

How to get the data into the variables? Depends on exactly how the data is stored in the database.

Note: to allow changes - please note that a checkbox form element is ONLY sent when the form is submitted IF IT IS CHECKED. An unchecked checkbox does not appear in the form collection, therefore you need to explicitly test for the checkbox …

if (isset ($_POST['economy']) {
  // Checkbox "economy" was checked
}

I use an array to put the checked fields into the field “Interests”. Each value is seperated by a comma: Energy, Economy, Housing

You can try something like this to parse the values into an array:

$raw_data="Energy, Economy, Housing";
$interests=explode(',',$raw_data);

foreach ($interests as $v){

   $checked[$v]=" checked='CHECKED' ";

}

Implimentation:

<input type=ckeckbox id=“Energy” name=“Energy” <?=$checked[‘Energy’] ?> …