Pass data from a table to an input to update

Asked

Viewed 346 times

-1

Good evening, I’m learning php and doing a CRUD to train, I was able to select in the table and the Insert to add new data, but I wanted to click the edit button, open a modal bootstrap (I already added) with the selected data inside the inputs for update (I don’t know how to do this part). Can anyone help me with this? I’m sorry if you already have a post talking about this.

php connection.

<?php
    $servidor = "localhost";
    $usuario = "root";
    $senha = "";
    $dbname = "locadora";    

    $conn = mysqli_connect($servidor, $usuario, $senha, $dbname);

    if(!$conn){
        die("Falha na conexao: " . mysqli_connect_error());
    }

    function conectaBanco(){
        $bd = mysqli_connect("localhost", "root", "", "locadora");
        return $bd;
    }
?> 

Table with edit button for modal in functios.php

<table class="table">
              <thead>
                <tr>
                  <th scope="col">Código</th>
                  <th scope="col">CPF</th>
                  <th scope="col">Nome</th>
                  <th scope="col">Salário</th>
                  <th scope="col">Ação</th>
                </tr>
              </thead>

            <tbody>
            <?php 
                foreach ($grupo as $row) { 
            ?>            
                <tr>
                  <th><?=$row["codigo"]?></th>
                  <td><?=$row["cpf"]?></td>
                  <td><?=$row["nome"]?></td>
                  <td><?=$row["salario"]?></td>
                  <td>
                    <div class="btn-group">
                        <form name="editar" method="POST">
                            <input type="hidden" name="idEditar" value="" />
                            <input class="btn btn-success" name="editar" type="button" value="Editar" data-toggle="modal" data-target="#exampleModal" data-whatever="Atualizar Funcionário">
                        </form>

                        <form name="deletar" action="../acao/excluir.php" method="POST">
                            <input type="hidden" name="idExcluir" value="" />
                            <input type="hidden" name="acao" value="excluir" />
                            <input class="btn btn-danger" name="deletar" type="submit" value="Deletar">
                        </form>
                    </div>
                  </td>
                </tr>           

                    <!-- Modal -->
                        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                          <div class="modal-dialog" role="document">
                            <div class="modal-content">

                              <!-- Modal Cabeçalho -->
                              <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLabel">Atualizar Funcionário</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                              </div>

                              <!-- Modal Corpo -->
                              <div class="modal-body">
                                <form method="POST" action="acao/atualizar.php" enctype="multipart/form-data">
                                  <div class="form-group">
                                    <input type="text" class="form-control" name="codigoFuncionario" placeholder="Código..." value="">
                                  </div>
                                  <div class="form-group">
                                    <input type="text" class="form-control" name="cpfFuncionario" placeholder="CPF..." value="">
                                  </div>
                                  <div class="form-group">
                                    <input type="text" class="form-control" name="nomeFuncionario" placeholder="Nome..." value="" >
                                  </div>
                                  <div class="form-group">
                                    <input type="text" class="form-control" name="salarioFuncionario" placeholder="Salário" value="" >
                                  </div>                                  
                                </form>
                              </div>

                              <!-- Modal Footer -->
                              <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                                <button type="button" class="btn btn-primary">Atualizar</button>
                              </div>

                            </div>
                          </div>
                        </div>

            <?php 
             }
            ?>

              </tbody>
            </table>

Only the function in the update.php table is missing to select the data and show inside the modal inputs.

1 answer

0


You have some errors in logic let’s go to them:

  1. The button editar table does not need to be within a form because it will only trigger the action of opening the modal.
  2. It is not necessary to have a modal for each row of the table. Only one modal is required for this, so the modal code needs to be out of the loop.

Once you already have an employee’s data in an array, just serialize it with json_encode and add it to the button that will trigger the modal. (in the example I chose the attribute name as data-funcionario but it could be data-qualquer-coisa)

How the jQuery.data api already parses json for us, we do not need to worry about it, just access $('button').data('funcionario') that an object will already come json to manipulate.

But for this to work it is very important that the attribute value data-funcionario button is created with simple quotes ' not to conflict with double quotes " json serialized by php.

Following the documentation bootstrap modal for this case we have:

<table class="table">
    <thead>
        <tr>
            <th scope="col">Código</th>
            <th scope="col">CPF</th>
            <th scope="col">Nome</th>
            <th scope="col">Salário</th>
            <th scope="col">Ação</th>
        </tr>
    </thead>

    <tbody>
    <?php foreach ($grupo as $row): ?>            
    <tr>
      <th><?php print $row["codigo"];?></th>
      <td><?php print $row["cpf"];?></td>
      <td><?php print $row["nome"];?></td>
      <td><?php print $row["salario"];?></td>
      <td>
        
        <button 
            type="button" 
            class="btn btn-success" 
            data-toggle="modal" 
            data-target="#exampleModal" 
            data-funcionario='<?php print json_encode($row)?>'>Editar</button>
        
        <form name="deletar" action="../acao/excluir.php" method="POST">
            <input type="hidden" name="idExcluir" value="<?php print $row['codigo']; ?>" />
            <input type="hidden" name="acao" value="excluir" />
            <input class="btn btn-danger" name="deletar" type="submit" value="Deletar">
        </form>
      </td>
    </tr>                   
    <?php endforeach; ?>
    </tbody>
</table>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

      <!-- Modal Cabeçalho -->
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Atualizar Funcionário</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <form method="POST" action="acao/atualizar.php">
      <!-- Modal Corpo -->
      <div class="modal-body">
          <div class="form-group">
            <input type="text" class="form-control" name="codigoFuncionario" placeholder="Código...">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" name="cpfFuncionario" placeholder="CPF...">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" name="nomeFuncionario" placeholder="Nome...">
          </div>
          <div class="form-group">
            <input type="text" class="form-control" name="salarioFuncionario" placeholder="Salário...">
          </div>                                  
      </div>

      <!-- Modal Footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
        <button type="submit" class="btn btn-primary">Atualizar</button>
      </div>
      </form>
    </div>
  </div>
</div>

And to finish the process of throwing the desired employee data to the modal we will need the following js:

<script>
$('#exampleModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget); // Button that triggered the modal
  var funcionario = button.data('funcionario'); // Extract info from data-* attributes
  console.log(funcionario);

  var modal = $(this);
  modal.find('[name="codigoFuncionario"]').val(funcionario.codigo);
  modal.find('[name="cpfFuncionario"]').val(funcionario.cpf);
  modal.find('[name="nomeFuncionario"]').val(funcionario.nome);
  modal.find('[name="salarioFuncionario"]').val(funcionario.salario);
});
</script>

References:

  • Thanks. Great explanation and the script worked perfectly.

  • It only updates one row of the table. Let’s say there are 5 employees in the table, it only updates 1, if I click on the others, will appear the data all right in the modal, but does not update the others, only 1

  • Yes, you cannot update user data with id 2 by filling in id 1 data

Browser other questions tagged

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