Save checked box in an array!

-1

I want, when selecting multiple checkboxes, these values are saved in an array, so that it is saved in the database. If I leave the checkboxes with the same id, as follows:

<div class="form-group">
          <label style="margin-bottom: 10px"> Dias disponíveis 
          </label><br />
            <label><input type="checkbox" name="dias" id="dias" 
value="Segunda-Feira">  Segunda-Feira</label><br />
            <label><input type="checkbox" name="dias" id="dias" 
value="Terça-Feira">  Terça-Feira</label><br />
            <label><input type="checkbox" name="dias" id="dias" 
value="Quarta-Feira">  Quarta-Feira</label><br />
            <label><input type="checkbox" name="dias" id="dias" 
value="Quinta-Feira">  Quinta-Feira</label><br />
            <label><input type="checkbox" name="dias" id="dias" 
value="Sexta-Feira">  Sexta-Feira</label>
          </div>

The php already understands and places the marked options in the array directly after the submit using:

$chgeckboxes = $_POST['checkbox'];

Can anyone help?

    
asked by anonymous 07.09.2017 / 16:36

1 answer

0

As already mentioned, you should not use elements with the same id in a document.

In your case the correct one is to use a pair of brackets [] at the end of the name attribute name="dias[]" . In this way elements of the same name are treated as an array.

HTML

<form action="" method="post"> 
<div class="form-group">
    <label style="margin-bottom: 10px"> Dias disponíveis 
    </label><br />
    <label><input type="checkbox" name="dias[]" value="Segunda-Feira">  Segunda-Feira</label><br />
    <label><input type="checkbox" name="dias[]" value="Terça-Feira">  Terça-Feira</label><br />
    <label><input type="checkbox" name="dias[]" value="Quarta-Feira">  Quarta-Feira</label><br />
    <label><input type="checkbox" name="dias[]" value="Quinta-Feira">  Quinta-Feira</label><br />
    <label><input type="checkbox" name="dias[]" value="Sexta-Feira">  Sexta-Feira</label>
    <input type="submit">
</div>
</form>

And in PHP

if(!empty($_POST['dias']) && count($_POST['dias']) ){
   $chgeckboxes = $_POST['dias'];
   //print_r($chgeckboxes);


}
    
07.09.2017 / 20:09