Update checkbox in array

0

I came across a situation I can not get around.

I need to update a MySQL database field where its display is a checkbox .

I'll try to exemplify:

A search brings up a series of records, where after I checkboxes and click the "Confirm Conference" button, all records listed on this page should be updated according to checkbox checked, that is, only the checkbox field will be updated. Follow the image showing the screen that already exists.

Thecodeformypageisthis:

<html><body><divid="main" class="container-fluid">
    <div id="top" class="row" style="margin-top: 50px">
        <div class="col-sm-4">
            <h3>Conferência do Depósito</h3>
        </div>
    </div> <!-- /#top -->
    </br>

    <div id="conf_deposito" class="row">    
    <div class="table-responsive col-md-12">
        <table class="table table-striped table-bordered " width="100%" id="tabela_datatables">
            <thead>
                <tr>
                    <th>Conferir</th>
                    <th>Nome</th>
                    <th>Tombamento</th>
                    <th>Quantidade</th>
                </tr>
            </thead>

            <tbody>
            <?php
            //Verifica se já existem registros com a mesma data do sistema. Se não existir, executa a cópia da tabela.
            $sis_data = date("Y/m/d");
            $unic = "SELECT * FROM conf_material WHERE data = '$sis_data'";
            $unic = $pdo->query($unic);
            if($unic->rowCount() < 1) {

            //Ao carregar a página, executa uma cópia dos registros para conferência.
            $cop = "INSERT INTO conf_material  (nome, tombamento, quantidade, local) SELECT nome, tombamento, quantidade, local FROM lista_geral WHERE local = 'deposito'";
            $cop = $pdo->query($cop);

            //Atualiza o campo de data para o data do dia.
            $atualiza_data = "UPDATE conf_material SET data = '$sis_data' WHERE data = '0000-00-00'";
            $atualiza_data = $pdo->query($atualiza_data);
            }

            if(isset($_POST['nome']) && empty($_POST['nome']) == false) {
                $nome = addslashes($_POST['nome']);
                $tombamento = addslashes($_POST['tombamento']);
                $quantidade = addslashes($_POST['quantidade']);
                $conferir = addslashes($_POST['conferir']);

                $sql = "UPDATE conf_material SET conferir = '$check_confirm'";
                $pdo->query($sql);
            }

            $sql = "SELECT * FROM conf_material WHERE local = 'Deposito' AND data = '$sis_data'";
            $sql = $pdo->query($sql);
            if($sql->rowCount() > 0) {
                foreach ($sql -> fetchAll() as $conf_deposito) { ?>
                    <tr>
                        <td class="actions">
                        <input type='checkbox' id="check_confirm" name="check_confirm" value="1" class='btn btn-success btn-xs' data- data-toggle="modal"></button></a>
                        </td>
                        <td><?php echo $conf_deposito['nome']; ?></td>
                        <td><?php echo $conf_deposito['tombamento']; ?></td>
                        <td><?php echo $conf_deposito['quantidade']; ?></td>
                    </tr>
                <?php } ?> <!-- Fecha foreach -->
            <?php } ?> <!-- Modal de IF rowcount -->    

    <form method="POST">
    <div class="row">
      <div class="form-group col-md-4">
        <input type="submit" value="Confirmar Conferência" class="btn btn-primary" />
        <a href="lista_geral.php" class="btn btn-default">Limpar</a>
    </div>
</form>

        </tbody>
    </table>

<!-- Rodapé -->
<?php require "rodape.php"; ?>
</body>
</html>

Does anyone have any idea how I can do this?

    
asked by anonymous 01.10.2017 / 05:22

2 answers

1

Your script looks more like a puzzle with a set of seven errors! :)

Initial Considerations

The form tag should involve all fields to be submitted:

<form method="POST">
<table class="table table-striped table-bordered " width="100%" id="tabela_datatables">
............
............
</table>
</form>

No foreach ($sql -> fetchAll() as $conf_deposito) {

should look like this:

<tr>
  <td class="actions">
    <input type='checkbox' id="check_confirm" name="check_confirm[]" value="<?php echo $conf_deposito['id'] ?>" class='btn btn-success btn-xs' data- data-toggle="modal">
  </td>
  

In the name attribute, at the end of its name, you must place brackets, indicating that more than one value can be sent to the same field. On the server side, an array with these elements will be sent.

Final code - comments in the code itself

<html>
<body>
 <div id="main" class="container-fluid">
    <div id="top" class="row" style="margin-top: 50px">
        <div class="col-sm-4">
            <h3>Conferência do Depósito  </h3>
        </div>
    </div> <!-- /#top -->

    <?php

        //**********conexão*********
                $hostname="localhost";  
                $username="USUARIO";  
                $password="SENHA";  
                $db = "NOME_DB";  
                $pdo = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
        //**********conexão*********                

            $sis_data = date("Y/m/d");

            //quantidade de registros retornados
            $Registros = $pdo->query("SELECT COUNT(*) FROM conf_material WHERE local = 'Deposito' AND data = '$sis_data'");
            $total = $Registros->fetchColumn();

            //para uso no formulário Resultados Por Pagina
            $quarto=(int)($total/4);

            if($_POST["resultadosPorPagina"]){
                $resultadosPorPagina=$_POST["resultadosPorPagina"];
            }else{
                $resultadosPorPagina=(2*$quarto);
            }

    ?>

    </br>
    <form action="" method="POST">
        <select name="resultadosPorPagina" size="1" onchange="this.form.submit()">
        <option>Resultados Por Pagina</option>
        <option value="<?php echo $quarto ?>"><?php echo $quarto ?></option>
        <option value="<?php echo 2*$quarto ?>"><?php echo 2*$quarto ?></option>
        <option value="<?php echo 3*$quarto ?>"><?php echo 3*$quarto ?></option>
        <option value="<?php echo $total ?>" >Todos</option>
        </select>
    </form>

    <div id="conf_deposito" class="row">    
    <div class="table-responsive col-md-12">
        <form action="" method="POST">
        <table class="table table-striped table-bordered " width="650" id="tabela_datatables">
            <thead>
                <tr>
                    <td width="100px"></td>
                    <td width="200px">Nome</td>
                    <td width="50px">Conferir</td>
                    <td width="200px">Tombamento</td>
                    <td width="100px">Quant</td>
                </tr>
            </thead>
            <tbody>
            <?php 

            //Verifica se já existem registros com a mesma data do sistema. Se não existir, executa a cópia da tabela.
            $sis_data = date("Y/m/d");
            $unic = "SELECT * FROM conf_material WHERE data = '$sis_data'";
            $unic = $pdo->query($unic);
            if($unic->rowCount() < 1) {

            //Ao carregar a página, executa uma cópia dos registros para conferência.
            $cop = "INSERT INTO conf_material  (nome, tombamento, quantidade, local) SELECT nome, tombamento, quantidade, local FROM lista_geral WHERE local = 'deposito'";
            $cop = $pdo->query($cop);

            //Atualiza o campo de data para o data do dia.
            $atualiza_data = "UPDATE conf_material SET data = '$sis_data' WHERE data = '0000-00-00'";
            $atualiza_data = $pdo->query($atualiza_data);
            }

            if(isset($_POST['check_confirm']) && empty($_POST['check_confirm']) == false) {

                $check_confirm = $_POST['check_confirm'];

                //vindo do input hidden que está antes da tag de fechamento form no final da pagina
                $ids=$_POST['arrayId'];
                $explodeIds = explode(',', $ids);

                $count=count($check_confirm);

                //aqui são feitos os UPDATES na coluna conferir com valor = 1 dos checkboxes que foram marcados
                for($i=0;$i<$count;$i++){ 

                    $check = $check_confirm[$i];

                     $sql = "UPDATE conf_material SET conferir='1' WHERE id='$check'"; 
                     $pdo->query($sql);

                //aqui são retirados os ids do array que serviram para a clausula WHERE do update acima
                        $key = array_search($check, $explodeIds);
                        if($key!==false){
                            unset($explodeIds[$key]);
                        }

                }

                //aqui são feitos os UPDATES na coluna conferir com valor = 0 cujo checkboxes não foram marcados
                foreach ($explodeIds as $val) { 
                    $sql = "UPDATE conf_material SET conferir='0' WHERE id='$val'"; 
                     $pdo->query($sql);
                }

            }

            $sql = "SELECT * FROM conf_material WHERE local = 'Deposito' AND data = '$sis_data' limit $resultadosPorPagina";
            $sql = $pdo->query($sql);
            if($sql->rowCount() > 0) {

                //este array conterá os ids que figuram nos checkboxes
                $listStr = Array();

                foreach ($sql -> fetchAll() as $conf_deposito) { 

                    $listStr[] = $conf_deposito["id"];

             ?>
                    <tr>
                        <td class="actions">

                        <!--os values destes checkboxes são os ids que servirão para a clausula WHERE dos UPDATES-->
                        <input type='checkbox' id="check_confirm" name="check_confirm[]" value="<?php echo $conf_deposito['id'] ?>" class='btn btn-success btn-xs' data- data-toggle="modal">

                        </td>
                        <td><?php echo $conf_deposito['nome']; ?></td>
                        <td><?php echo $conf_deposito['conferir']; ?></td>
                        <td><?php echo $conf_deposito['tombamento']; ?></td>
                        <td><?php echo $conf_deposito['quantidade']; ?></td>
                    </tr>
                <?php } ?> <!-- Fecha foreach -->
            <?php } ?> <!-- Modal de IF rowcount -->    

    <div class="row">

      <div class="form-group col-md-4">
        <input type="submit" value="Confirmar Conferência" class="btn btn-primary" />
        <!--a href="lista_geral.php" class="btn btn-default">Limpar</a--><br>
      </div>
    </div>

        </tbody>
    </table>

    <!-- input cujo value é a relação de ids constantes nos checkbox desta página -->
    <?php
       $listStr = implode(",",$listStr);
    ?>
    <input type="hidden" name="arrayId" value="<?php echo $listStr; ?>">
</form>

</body>
</html>
  

This script works according to a% of author%

"click the" Confirm Conference "button, only the chackbox field - of all records - would be updated at the same time ( with 0 or 1 depending on whether the field was marked or not ). "

    
01.10.2017 / 08:02
-1

Good afternoon, Leo Caracciolo ...

Sorry for the mess ... I'll try to explain better what I need:

I have a select that brings a series of records. Here, I need to apply a flag (number 1 in bd) and that in my head, the best way would be to use a checkbox field, so that when the user marks the checkbox and then clicks the " Confirm Conference ", only the chackbox field - of all records - would be updated at the same time (with 0 or 1, depending on whether the field was checked or not). I hope I explained it better ... Thanks for the help! I'm breaking my head here too, while I'm waiting!

    
02.10.2017 / 19:09