How Do I Insert The Value From A Checkbox Into Mysql In Php?
Solution 1:
First of all I would change these
<form method="post">
<inputtype="hidden" name="blah" value="blah">
<inputtype="checkbox" name="cbox[]" value="1">
<inputtype="checkbox" name="cbox[]" value="1">
<inputtype="checkbox" name="cbox[]" value="1">
<inputtype="checkbox" name="cbox[]" value="1">
<inputtype="checkbox" name="cbox[]" value="1">
<button type="submit">Submit</button>
</form>
As you wont be able to tell severside which one is checked currently you'll get something like this if only one of them is checked, in the $_POST
array(
'blah' => 'blah', //your hidden field'cbox' => array(
0 => 1
)
);
And if 2 are checked
array(
'blah' => 'blah', //your hidden field'cbox' => array(
0 => 11 => 1
)
);
But the question is which 2? So you will either need to change the names of these or the values
<inputtype="checkbox" name="cbox[]" value="1">
<inputtype="checkbox" name="cbox[]" value="2">
<inputtype="checkbox" name="cbox[]" value="3">
<inputtype="checkbox" name="cbox[]" value="4">
<inputtype="checkbox" name="cbox[]" value="5">
OR
<inputtype="checkbox" name="cbox1" value="1">
<inputtype="checkbox" name="cbox2" value="1">
<inputtype="checkbox" name="cbox3" value="1">
<inputtype="checkbox" name="cbox4" value="1">
<inputtype="checkbox" name="cbox5" value="1">
OR if you want to further complicate things
<inputtype="checkbox" name="cbox[cbox1]" value="1">
<inputtype="checkbox" name="cbox[cbox2]" value="1">
<inputtype="checkbox" name="cbox[cbox3]" value="1">
<inputtype="checkbox" name="cbox[cbox4]" value="1">
<inputtype="checkbox" name="cbox[cbox5]" value="1">
Depending on what one you pick, you will need to then check if it is set, if the checkbox is not checked it wont be sent to the sever. There are a few ways around this depending how you name or do the values. The best approach is simply using
$cbox1 = isset( $_POST['cbox1'] ) ? 1 : 0; //if you rename them///or -- ( or something similar for each if you change the value )if( in_array( 1, $_POST['cbox'] )){
$cbox1 = 1
}else{
$cbox1 = 0;
}
Now which one you pick to do should depend on if the number of checkboxes is known, a fixed number, or dynamic. If it's a fixed number I would change the name ( the 2nd option ) as it is cleaner and will be much easier to deal with server side.
Solution 2:
If HTML components are in these arrangement
<inputtype="checkbox" name="chkBx1" value="1">
<inputtype="checkbox" name="chkBx2" value="2">
in demo.php
functioncheckStatus($elementID) {
if (array_key_exists($elementID, $_POST)) {
$status = 1;
} else {
$status = 0;
}
return$status;
}
sql="INSERT INTO freetrail (cbox1, cbox2, cbox3,cbox4)VALUES ($this->chkEditStatus('chkBx1'),($this->chkEditStatus('chkBx1'), ($this->chkEditStatus('chkBx2'), ($this->chkEditStatus('chkBx3'),($this->chkEditStatus('chkBx4'))";
Post a Comment for "How Do I Insert The Value From A Checkbox Into Mysql In Php?"