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??

 

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.