How do I get the value of each checkbox that’s inside a loop?

Asked

Viewed 188 times

1

Good morning guys, I need help :( The thing is, I need to delete several records at once so I need to select the ID of each record, so I did an input with checkbox inside the loop this way:

<form method="POST" id="formDeletarMsg" action="deletarMsg.php">
   <input type="checkbox" name="msg[]" value="<?php echo $idMsg; ?>">                          
</form>

Button Submit is out of the form, I am using javascript as it will be in the footer of Section.

And I’m using a foreach to display the data of each checkbox, it even works, only it displays only the first checkbox marked, if I mark the second or the third does not display anything, if I mark the first displays:

if(isset($_POST['msg'])){
$msg = $_POST['msg'];
foreach($msg as $key => $value){
    echo $key . "<br>";
    echo $value;
}
var_dump($value);
}

1 answer

3


Guys, the mistake I made was to put the form inside the while, so it was only displaying the first checkbox marked, the form has to be outside the while but the input has to be inside. RESOLVED!!!

<form method="POST" id="formDeletarMsg" action="deletarMsg.php">
                <?php
                    while($row = mysqli_fetch_array($sqlMps)):
                        $idMsg = $row['idMsg'];
                        $assunto = utf8_encode($row['assunto']);
                        $usuario = $row['usuario'];
                        $visualizou = $row['visualizou'];
                        $dataMsg = utf8_encode($row['dataMsg']);

                ?>
                <li>
                    <span><a <?php if($visualizou == 0){ echo "class='negrito'";}?> href="visualizarMp.php?id=<?php echo $idMsg; ?>"><?php echo substr($assunto, 0, 30); ?></a>   por <strong><?php echo $usuario; ?></strong> - <?php echo $dataMsg; ?></span>
                    <div class="right">

                            <input type="checkbox" name="deletar[]" value="<?php echo $idMsg; ?>">


                    </div>
                </li>

                <?php
                    endwhile;
                ?>
                 </form>
  • Hello Vinicius, you don’t want to post a piece of code to help other users who have the same problem?

  • Just take the form out of the loop, I’ll edit my answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.