Page 1 of 1

Processing a checkbox form

Posted: Wed May 26, 2010 11:23 am
by tom8521
I have a form, but don't know how to process the clicked checkboxes and add the information to a database.

My HTML form is like this:

<form action="availability.php" method="post">
<input type="checkbox" name="mon9-11" value="mon9-11" />
<input type="checkbox" name="mon11-1" value="mon11-1" />
<input type="checkbox" name="mon1-3" value="mon1-3" />
<input type="checkbox" name="mon3-5" value="mon3-5" />
<input type="checkbox" name="mon5-7" value="mon5-7" />
<input type="checkbox" name="mon7-9" value="mon7-9" />
<input type="submit" name="submit" value="Done" />
<input type="hidden" name="submitted" value="TRUE" />
</form>

I'm against the clock on this, please help!

Re: Processing a checkbox form

Posted: Wed May 26, 2010 2:04 pm
by dimxasnewfrozen
I typically do something like this:


Form:

Code: Select all

<form action="availability.php" method="post">
         <input name="my_checkbox[]" type="checkbox"  value="Val1" /> Val1<br>
         <input name="my_checkbox[]" type="checkbox"  value="Val2" /> Val2<br>
         <input name="my_checkbox[]" type="checkbox"  value="val3" /> Val3<br>
        <input type="submit" name="submit" value="Done" />
       <input type="hidden" name="submitted" value="TRUE" />
</form> 

availability.php:

Code: Select all

	foreach ($_POST['my_checkbox'] as $k=> $c){
		// run DB statements. (Insert, update, delete, etc...)

	}

Re: Processing a checkbox form

Posted: Thu May 27, 2010 3:45 am
by tom8521
I don't understand what the $K and $C bit is doing on here :(

Re: Processing a checkbox form

Posted: Thu May 27, 2010 4:22 am
by Apollo
That way you'll only get the checked checkboxes, because the unchecked ones won't appear in $_POST at all (rather than false or 0 or anything).
Besides, it's unnecessary clutter/redundancy to
- repeat the same string for name and value
- repeat the same html for all checkboxes

The general idea is if you wish to add or change a checkbox item, you have to add or change ONE string, not duplicating redundant stuff.

I'd rather do something like this:

options.php:

Code: Select all

<?php
$list = array('mon3-5','mon5-7','mon7-9');
?>
form.php:

Code: Select all

<form action='availability.php' method='post'>
<?php
include('options.php');
foreach($list as $c)
{
  ehco "<input type='checkbox' name='$c' value='1' />$c<br />";
}
?>
<input type='submit' name='submit' value='Done' /></form>
availability.php:

Code: Select all

<?php
include('options.php');
foreach($list as $c)
{
  $v =  $_POST[$c] ? 1 : 0;
  $query .= "$c = $v, ";
}
print($query); // or whatever you need to do with them
?>