Jump to content

Checkbox value from database


totalx

Recommended Posts

Hello again,

 

I have a form that has several options to select features of a computer (vga, dvi, ethernet, modem, zip, etc.) through checkboxes. In the database, it is stored as a 0/1 (false/true). What I am working on is an edit form to make changes if necessary, but I am having trouble populating the checkboxes that are marked as true already.

 

while($cmp = $_SESSION['DB']->fetch_array($cmpQ)){
$chkbxs = array('vga', 'ps2', 'usb', 'firewire', 'ethernet', 'cddvd', 'fdd', 'zip', 'dvi', 'serial', 'sound', 'wireless', 'modem', 'smartm');
foreach ($chkbxs as $value) {
	$check="";
	if ($cmp[$value] == 1) {
		$check = "checked";
		echo ''.$value.' <br/>';
	}
...more code, form below

 

This does it it should. I have an entry with vga, firewire, smartm, and zip selected, and $value returns that properly.

 

In the form, this is how I have it set up.

echo '<input type="checkbox" name="hardware[]" value="vga" '.$check.'>';

 

Right now, every checkbox is selected, meaning that for some reason, $cmp[$value] == 1 is affecting all checkboxes in the form, even though it is only returning the 4 that are marked as selected when I echo $value.

 

Am I missing something minor or am I going about this the wrong way?

 

 

Link to comment
https://forums.phpfreaks.com/topic/255779-checkbox-value-from-database/
Share on other sites

Quite frankly they both do the same thing. By standards, I believe yes, it should be checked="checked" and I have made that change. But it is still populating every box as checked, and I am stumped as to why.

 

Each of those values in the array are columns in my database. I wasn't sure how to effectively go about getting the value of each one, individually. I feel like I am just missing something small, seeing as how $value is returning all 4 that I have marked in the DB.

 

I'm going to keep plugging away at it. Any other suggestions or ways to possibly clean this up would be appreciated :)

Oh, I see. You would need to put your checkboxes inside the foreach loop. Like..

foreach ($chkbxs as $value) {
	$check="";
	if ($cmp[$value] == 1) {
		$check = "checked";
		echo ''.$value.' <br/>';
	}

                echo '<input type="checkbox" name="hardware[]" value="' . $value . '" '.$check.'>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.