By Sergey Skudaev
Recently, I used HTML form with array of check boxes. Previously, I wrote about ussing array of text input type. It is easy: on the form you just add brakets to the input text name fields.
print('<form name="arrayoffields" method="post" action="act_submit_check.php">'); for($i=0; $i<$count; $i++) { print('<input type="text" name="lastname[]" size="15"/>'); print('<input type="checkbox" name="confirm[]" />'); } print('<input type="hidden" name="count" value="'.$count.'"/>'); print('<input type="submit" name="submit" value="Submit"/>'); print('</form>');
$lastname=array(); $confirm=array(); $count=0; if(isset($_POST['lastname'])); $lastname=$_POST['lastname']; if(isset($_POST['confirm'])); $confirm=$_POST['confirm']; if(isset($_POST['count'])); $count=$_POST['count']; for($i=0; $i<$count; $i++) { $sql="insert into mytable(name, confirm) values
('".$lastname[$i]."', '".$confirm[$i]."')"; ....some code........ }
The lastname array will have size of 10, but the confirm array of check boxes will have size of 3, because only 3 check boxes are marked. Visitor confirmed the first, the fourth and the seventh records, but in database wrong data will be inserted because the first, the second and the third element of checkboxes array will have value and no more elements of check boxes array will exist.
To fix the problem you have to assign an index and a unique value to each check box field. I use count.
print('<form name="arrayoffields" method="post" action="act_submit_check.php">'); for($i=0; $i<$count; $i++) { print('<input type="text" name="lastname[]" size="15"/>'); print('<input type="checkbox" name="confirm['.$count.' ]" value="'.$i.'"/ >'); } print('<input type="hidden" name="count" value="'.$count.'"/ >'); print('<input type="submit" name="submit" value="Submit"/>'); print('</form> ');
Now your array of check boxes has 10 elements even if not all of them are marked.
for($i=0; $i<$count; $i++) { $markconfirm=0; if($confirm[$i] !="") $markconfirm=1; $sql="insert into mytable(name, confirm) values ('".$lastname[$i]."', '".$markconfirm."')"; if(!mysql_query($usql)) { echo mysql_errno() . ": "; echo mysql_error() . "<br>"; } else echo "Record inserted";
That is how you have to use array of check boxes on HTML form.
Alternatively, you may use text input instead of checkbox. JavaScript allows "mark" or "unmark" text input with 'X':
<input type="text" value="<?php echo $x; ?>" name="mycheckbox[]" id="mycheckbox" style="width:12px; height:12px;" onclick="if(this.value=='') this.value='X'; else this.value='';" />