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!
Processing a checkbox form
Moderator: General Moderators
-
dimxasnewfrozen
- Forum Commoner
- Posts: 84
- Joined: Fri Oct 30, 2009 1:21 pm
Re: Processing a checkbox form
I typically do something like this:
Form:
availability.php:
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
I don't understand what the $K and $C bit is doing on here 
Re: Processing a checkbox form
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:
form.php:
availability.php:
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');
?>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>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
?>