Jump to content

[SOLVED] Automatic check for selected checkboxes


Akira

Recommended Posts

Ok, I know it must be some simple thing that I am doing wrong, but just can't find it :| maybe you guys have a clue :)

 

I have a basic form with checkboxes, which i store in a field with PHP's function serialize().

I view the checkboxes with the following function i wrote;

 

function SelectCheckbox($id,$field){		

$id = unserialize($id);

$owner_q="SELECT * FROM $field ORDER BY name ASC";
$owner_r= mysql_query($owner_q);
while ($row = mysql_fetch_array($owner_r)) {  
	$p_name = $row['name'];
	$p_id = $row['id'];

	for ($i=0; $i<count($id); $i++) {
		$checked = (($p_id==$id[$i]) ? 'checked="checked"' : null);		
	} 
	print "<input type='checkbox' name='db[]' value='$p_id' $checked style='border:0px;'>$p_name <br>";			


}
} // end function

 

So first i get the array with id's stored in the DB to match = $id= unserialize($id);.

Then i do a while loop to get the names from the DB for the checkboxes + id's.

And a for loop to check the id's from the array with the id's from the DB, when matched, it should echo the checkbox as checked.

 

Now, only the last checked box is echo's as checked.

What am i doing wrong here??

 

 

Just do it in the query...

 


function SelectCheckbox ( $id, $field )
{
$owner_q="SELECT id, name, IF(id IN('" . implode ( "', '", unserialize ( $id ) ) . "'), ' checked="checked"', '') AS checked FROM $field ORDER BY name ASC";

$owner_r= mysql_query ( $owner_q );

while ( $row = mysql_fetch_array ( $owner_r ) )
{
	echo "<input type='checkbox' name='db[]' value='" . $row['id'] . "'" . $row['checked'] . " style='border:0px;'>" . $row['name'] . "<br />";
}
} // end function

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.