checkbox arrays php

virtualk

Active Member
Joined
Jan 1, 2012
Messages
63
Reaction score
0
Hi

Im using the following code to create checkboxes in a form. What I need, is the boxes the user checked, to remain checked after the form has been submitted. The reason for this is so that the user will not have to re-check the boxes if they would like to submit the form again. How can I do this using php code ?

PHP:
if ($db_found) {

	$sql="select cname, cid from course";

	//query the database
	$rs=mysql_query($sql) or die($sql.">>".mysql_error());

	//count how many records found
	$num=mysql_num_rows($rs);

if($num>0){ //check if
<FORM NAME ="form1" METHOD ="POST" ACTION ="student_reg.php">
//create array loop
	while($row=mysql_fetch_array($rs)){

		// extract row and echo the array
		extract($row);

	echo "$cname"."<Input type = 'Checkbox' Name ='chk1[]' value ='$cid'>";

}

	<INPUT TYPE = "Submit" Name = "Submit1"  VALUE = "Register">


	</FORM>
}

}
 
PHP:
echo "$cname"."<Input type = 'Checkbox' Name ='chk1[]' value ='$cid' checked=".$_POST[checkboxid].isempty ? "" : "checked".">";
or whatever teh syntax is??
 
Last edited:
What kabal said, replace his last condition with:

Code:
  (isset($_POST['checkkboxid'])

But why not just have a pop-up asking if the user wants to submit again? :p

Else you need to have a loop that runs through all your submitted values to see what was checked for submission and reload the check box list with "checked" parameters - unnecessary use of resource/db communication.
 
I prefer to use array_key_exists. This is a bit longer to write but is much better and won't throw any warnings

Code:
echo ( array_key_exists($checkboxid, $_POST) && $_POST[$checkboxid]) == true ?  'checked' : '');

My development environment is set to strict and throws warnings with isset, also remember isset will return false even if the key exists but has the value null.
 
I prefer to use array_key_exists. This is a bit longer to write but is much better and won't throw any warnings

Code:
echo ( array_key_exists($checkboxid, $_POST) && $_POST[$checkboxid]) == true ?  'checked' : '');

My development environment is set to strict and throws warnings with isset, also remember isset will return false even if the key exists but has the value null.

+1.

Or do what I do... the above, but with the above in a function.
 
Top
Sign up to the MyBroadband newsletter
X