0

Need help. i have 5 checkboxes[] 3 is checked 2 unchecked

i want to insert all checkbox values but if checkbox is checked than insert value 1 and if unchecked insert 0

   <input id="answer" type="text" name="answer[]" /> //checked
   <input id="answer" type="text" name="answer[]" />
   <input id="answer" type="text" name="answer[]" /> /checked
   <input id="answer" type="text" name="answer[]" />
   <input id="answer" type="text" name="answer[]" /> //checked

if i check the length or size of field than it displays and insert only checked items but i want to insert unchecked also with value 0

Muhammad Kazim
  • 611
  • 2
  • 11
  • 26
  • 1
    That HTML does not show any checkboxes? Thats a little confusing – RiggsFolly Jun 20 '20 at 12:00
  • 1
    Did you know that an `id` must be unique on a page. So having 5 `id="answer"` is not legitimate HTML code – RiggsFolly Jun 20 '20 at 12:01
  • Does this answer your question? [How get value for unchecked checkbox in checkbox elements when form posted?](https://stackoverflow.com/questions/19239536/how-get-value-for-unchecked-checkbox-in-checkbox-elements-when-form-posted) – desertnaut Jun 20 '20 at 23:49

1 Answers1

1

The browser does not send unchecked checkbox data to the server, PHP in this case.

So in your PHP you have to know about all the checkboxes that exist on your form and check for the existance of each to decide what to store to your database.

So something like

HTML

<input type="checkbox" name="cb1" value="1" /> //checked
<input type="checkbox" name="cb2" value="2" />
<input type="checkbox" name="cb3" value="3" /> /checked
<input type="checkbox" name="cb4" value="4" />
<input type="checkbox" name="cb5" value="5" /> //checked

if (isset($POST['cb1'])) {
    $cb1 = $POST['cb1'];
}else{
    // it was not checked because it was not sent
    // so use the default or whatever UNCHECKED value when storing to the DB
    $cb1 = 0;   // for example
}

You can shorten that code a bit by doing

$cb1 = isset($POST['cb1']) ? $POST['cb1'] : 0;
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149