Pick line data with checked checkbox

2

I have the code below and I want the array nome to contain only the names of the lines that have checkbox cb checked.

<form action="" method="post">
    <table>
        <tr>
            <td><input type="checkbox" name="cb[]" id="cb1" value="1"></td>
            <td><input type="text" name="nome[]" id="nome1"></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="cb[]" id="cb2" value="1"></td>
            <td><input type="text" name="nome[]" id="nome2"></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="cb[]" id="cb3" value="1"></td>
            <td><input type="text" name="nome[]" id="nome3"></td>
        </tr>
    </table>
    <input type="submit" value="enviar" name="enviar">
</form>

<?php
    if (isset($_POST['enviar'])) {
        var_dump($_POST['cb']);
        var_dump($_POST['nome']);
    }
?>
    
asked by anonymous 05.10.2018 / 21:14

1 answer

0

The simplest way to interact with an array would be to use foreach , but in your In case, it would be better to use a for because when finding a "checked" item, we get the value name with the same index.

It would look something like this:

for ($i = 0; $i < count($_POST['cb']); $i++) {
   // verifica se está checado
   if(isset($_POST[$i]['cb']))  {
      // pega o nome de uma linha checada
      $nome = $_POST[$i]['nome']

      // aqui faz alguma coisa, como inserir ou atualizar no banco
   }
}
    
06.10.2018 / 17:21