Update checkbox in array

Asked

Viewed 507 times

0

I came across a situation I’m not getting around.

I need to update a field in Mysql database, where its display is a checkbox.

I will try to exemplify:

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

inserir a descrição da imagem aqui

The code on my page is this:

<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 -->
    </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 do it?

  • 1 - checkbox are out of form - 2 inputs have value = 1 always? 3 - In the name attribute, at the end of your name, you must place brackets, indicating that more than one value can be sent to the same field. on the server side, an array of these elements will be sent. 4 - Missing action in the form (send to the current page)

2 answers

1


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

Initial considerations

The form tag must involve all fields to be submitted:

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

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

should thus:

<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 your name, you must place brackets, indicating that more than one value can be sent to the same field. On the server side, an array of these elements will be sent.

Final code - comments on 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 resposta of the author

"click on 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 has been marked or not)."

  • Leo, unfortunately the update didn’t work. Nothing is inserted in the field conferir. :/ In addition, the paging script is not required, but will be saved for a possible need. Can help me update?

  • @emersonsbr I will test performing the querys

  • Ok, Leo! The Script worked, thank you very much! One last question, it is possible to run the script without that field nome is defined as <input type="text">, that is, using only <?php echo $conf_deposito['nome']; ?>??? I will pay attention to the organization of questions and comments.

  • @emersonsbr Yes, but this validation if(isset($_POST['nome']) && empty($_POST['nome']) == false) { shall be replaced by another which does not depend on $_POST['nome'] Can use if(isset($_POST['check_confirm']) && empty($_POST['check_confirm']) == false) {

  • I thank my colleagues for taking the time to help me, especially @Leocaracciolo who solved my doubt. I will give credit. Until next!

-1

Good afternoon, Leo Caracciolo...

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

I have a select that carries a series of records. Behold, in these records I need to apply a flag (number 1 in the bd) and that, in my head, the best way would be using a checkbox field, so that when the user checked the checkbox and then clicked on 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). I hope I explained it better... Thanks for the help! I’m cracking my head here too, while I wait!

Browser other questions tagged

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