0

Hi, I am building a web form which contains several groups of checkboxes with many items in each. I want to store these values in a database so they can be retrieved and updated when needed.

What would be the best way to store the information from a checkbox group so that i can then use it again to populate the selected checkboxes so it can be edited if needed, also how would i set them as checked?

2
Contributors
3
Replies
7
Views
5 Years
Discussion Span
Last Post by pjh1985
1

Use bits on value attribute and an array for the name attribute.

<?php
//---FORM HANDLING SCRIPT---//
//THIS USED TO UPDATE DB
$postcheck = 0;
if(isset($_POST['mychecks'])){
	$postcheck = array_sum($_POST['mychecks']);
	//e.g. 6 = second and third (2 + 4) checks selected
	//DO DB UPDATE - save postcheck to a field
}

//---FORM PAGE----//
$checkboxes = array(
				array('id'=>'myfirstcheck','value'=>1,'label'=>'FirstLabel'),
				array('id'=>'mysecondcheck','value'=>2,'label'=>'SecondLabel'),
				array('id'=>'mythirdcheck','value'=>4,'label'=>'ThirdLabel'),				
				array('id'=>'myfourthcheck','value'=>8,'label'=>'FourthLabel'),
);
//ideally the above would be created from a DB
?>


<!--FORM PAGE
USE DB TO GET dbpostcheck variable - e.g. 10 = second and fourth (2 + 8) checks selected-->
<?php
$checkboxes="";
foreach($checks as $check){
	$sel = ($check['value'] & $dbpostcheck) ? ' checked = "checked"': '';
	$checkboxes .= "<input type=\"checkbox\" name=\"mychecks[]\" id=\"{$check['id']}\" value=\"{$check['value']}\"{$sel} /> <label for = \"{$check['id']}\">{$check['label']}</label>\n";	
}
?>

<form ...>
 <?php echo $checkboxes;?>
</form>

not tested

Edited by diafol: n/a

0

I have had to adapt it slightly to fit my needs but it helped me a lot thanks.

The data was from an old website so i was not able to use the same value system as above. Here is what i came up with

<? 
$aGender = array("Male", "Female");
 
//converting comma separated into array using explode function
$dbGender= explode(',',$row_details['value']);
 
foreach ($aGender as $gender) {
	if(in_array($gender,$dbGender)) {
		echo "<input name=\"gender[]\" type=\"checkbox\" value=\"$gender\" CHECKED> $gender ";
    } 
	else{
      echo "a<input name=\"gender[]\" type=\"checkbox\" value=\"$gender\"> $gender";
    }
}
?>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.