How to use a single form to register a new user and change data of an existing user on the system?

Asked

Viewed 107 times

1

Hello. I have a form and table (which lists company employees).

When I click on a TR (from your respective employee) in the table, the form data is filled in with the company employee data. So, if I modify any employee data, I send the data to a PHP file and update the database table and update this employee’s data. So far so good. (That is, the "CHANGE" button that leads to the update is working normally)

Only I would like that when I DO NOT click from the table tr, and the form is blank, I enter data into it and register a new employee (perform an INSERT).

I’m breaking my head here. I thought about putting two submits buttons, one being "CHANGE" and the other being "REGISTER". And each of them call a different function from jQuery so I can use a specific AJAX that communicates with different PHP files.

But I’m not getting a good logic from it. If anyone can help me, I would appreciate it. (I believe it’s not something difficult)

Below follows the code I’m using so far.

$(document).ready(function() {

  // AO CARREGAR A PÁGINA, CHAMAR A FUNÇÃO QUE PREENCHE OS FUNCIONÁRIOS
  $(function() {
    preencher_funcionarios();

  });


  //Evento que ocorre ao submitar o formulário
  $('#formulario-cadastrar-funcionarios').submit(function(e) {
    e.preventDefault();
    var formulario_cadastrar_funcionarios = $(this);
    var retorno_cadastrar_funcionarios = cadastrar_funcionarios(formulario_cadastrar_funcionarios);

  });


  //Função que faz o cadastro do funcionário
  function cadastrar_funcionarios(cadastrarfuncionarios) {
    $.ajax({
      url: "banco/banco-vision/pagina-cadastrar-funcionarios/incluir-funcionarios.php",
      type: "post",
      data: cadastrarfuncionarios.serialize(),
      cache: false,

    }).done(function(retornousuarios) {
      var funcionarios = "";

      $.each($.parseJSON(retornousuarios), function(chave, funcionarios_cadastrados) {
        //Aqui atualizamos a tabela da lista dos funcionários
        //CRIANDO AS LINHAS COM OS TD DA TABELA QUE SÃO O RESULTADO NA CONSULTA AO BANCO 

        funcionarios += '<tr id="' + funcionarios_cadastrados.codigo + '">';

        funcionarios += '<td>' + funcionarios_cadastrados.usuario + '</td>';
        funcionarios += '<td>' + funcionarios_cadastrados.EMPRESA_ORIGEM + '</td>';
        funcionarios += '<td>' + funcionarios_cadastrados.departamento + '</td>';

        funcionarios += '</tr>';

      });

      $('#registros-funcionarios-cadastrados').html(funcionarios);

      alert(retornousuarios);

    }).fail(function() {
      console.log("Erro ao atualizar");

    }).always(function() {


    });

  }





});
<?php
	
	
	
	//CHAMANDO O ARQUIVO DE CONEXÃO COM O BANCO DE DADOS
	require_once("banco/conexao/conexao-com-banco.php"); 
	require_once("banco/validador-de-login/validador-login.php"); 
	
	
?>

  <?php

require_once("banco/banco-vision/pagina-cadastrar-funcionarios/preencher-select-departamento.php"); 

?>



    <!DOCTYPE html>

    <html>

    <head>
      <title>T-Vision</title>
      <meta http-equiv="X-UA-Compatible" content="IE-edge">
      <meta name="viewport" content="width=devide-width, initial-scale=1">
      <meta charset="UTF-8">
      <script src="_jQuery/jquery-3.2.1.min.js"></script>
      <!-- ARQUIVO JQUERY -->
      <link href="_css-cadastrar-funcionarios/pagina-cadastrar-funcionarios/cadastrar-funcionarios.css" rel="stylesheet">
      <!-- ARQUIVO CSS DO -->
      <link href="_bootstrap4.1.1/css/bootstrap.min.css" rel="stylesheet">
      <!-- ARQUIVO CSS DO BOOTSTRAP -->

    </head>


    <body>

      <!-- INTRODUÇÃO VIDEO - ANDREWS-->
      <!--
		<video autoplay muted loop id="myVideo">
  			<source src="_videos/Intro_Login.mp4" type="video/mp4">
		</video>
		-->

      <div class="container-fluid">

        <div class="row" id="row-filtros-funcionario">

          <!-- DIV COM O FORMULÁRIO DE LOGIN -->

          <div class="col-lg-8 col-lg-offset-2" id="cadastrar-funcionarios">

            <h2>INFORMAÇÕES DO FUNCIONÁRIO</h2>

            <form action="" method="post" id="formulario-cadastrar-funcionarios">

              <div class="form-group">
                <label for="usuario">Usuario:</label>
                <input class="form-control" type="text" id="usuario" name="usuario" placeholder="Digite o nome do usuário" required autofocus />
              </div>

              <div class="form-group">
                <label for="senha-usuario">Senha:</label>
                <input class="form-control" type="text" id="senha-usuario" name="senha-usuario" pattern="^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@#$])[a-zA-Z0-9@#$]{8,50}$" placeholder="Digite a senha do usuário" required />
                <span style="font-size: 70%">(A senha deve conter no mínimo uma letra maiúscula, uma minúscula, um número e um caracter especial (@, # ou $). A senha deve possuir no mínimo 8 caracteres.)</span>
              </div>

              <div class="form-group">
                <label for="email-usuario">Email:</label>
                <input class="form-control" type="email" id="email-usuario" name="email-usuario" placeholder="Digite o email do usuário" required />
              </div>

              <div class="form-group">
                <label for="departamento-usuario">Departamento:</label>
                <select class="form-control" name="departamento-usuario" id="departamento-usuario" required>
                  <?php
											while($linha_departamento = mysqli_fetch_assoc($lista_departamento))
											{
										?>
                    <option value="<?php echo $linha_departamento[" DEPARTAMENTO "];?>">
                      <?php echo $linha_departamento["DEPARTAMENTO"];?>
                    </option>

                    <?php
											}
										?>
                </select>
              </div>

              <div class="form-group">
                <label for="empresa-origem-usuario">Empresa Origem:</label>
                <select class="form-control" name="empresa-origem-usuario" id="empresa-origem-usuario" required>
                  <?php
											while($linha_empresa_origem = mysqli_fetch_assoc($lista_empresa_origem))
											{
										?>
                    <option value="<?php echo $linha_empresa_origem[" EMPRESA_ORIGEM "];?>">
                      <?php echo $linha_empresa_origem["EMPRESA_ORIGEM"];?>
                    </option>

                    <?php
											}
										?>
                </select>
              </div>

              <div class="form-group">
                <label for="tipo-usuario">Tipo de Usuário</label>
                <select class="form-control" name="tipo-usuario" id="tipo-usuario" required>
                  <option id="usuariocomum" value="usuariocomum">USUARIO COMUM</option>
                  <option id="supervisor" value="supervisor">SUPERVISOR</option>
                  <option id="administrador" value="administrador">ADMINISTRADOR</option>
                </select>
              </div>

              <div class="form-group">
                <label for="status-usuario">Status do Usuário</label>
                <select class="form-control" name="status-usuario" id="status-usuario" required>
                  <option id="ativo" value="ativo">ATIVO</option>
                  <option id="inativo" value="inativo">INATIVO</option>
                </select>
              </div>

              <input type="hidden" name="cod-funcionario" id="cod-funcionario" value="1000">

              <div class="form-group">
                <input class="btn btn-md btn-primary" type="submit" name="cadastrar-funcionarios" id="cadastrar-funcionarios" value="CADASTRAR FUNCIONÁRIO">
              </div>

              <div class="form-group">
                <input class="btn btn-md btn-success" type="submit" name="salvar-funcionarios" id="salvar-funcionarios" value="ALTERAR FUNCIONÁRIO">
              </div>

              <div class="form-group">
                <input class="btn btn-md btn-danger" type="reset" name="resetar-campos" id="resetar-campos" value="LIMPAR">
              </div>


            </form>

            <div id="mensagem">
              <h5>
                <?php echo $mensagem ?>
              </h5>
            </div>

          </div>

        </div>


        <div class="col-lg-8 col-lg-offset-2" id="listagem-funcionarios">

          <table class="table table-bordered table-condensed table-hover" id="resultado-funcionarios-cadastrados">

            <thead class="">
              <tr>
                <th>FUNCIONÁRIO</th>
                <th>EMPRESA</th>
                <th>DEPARTAMENTO</th>
              </tr>
            </thead>

            <tbody id="registros-funcionarios-cadastrados">

            </tbody>

          </table>

        </div>


      </div>

      <script src="_jquery/jquery-3.2.1.min.js"></script>
      <!-- ARQUIVO JQUERY -->
      <script src="_bootstrap4.1.1/js/bootstrap.min.js"></script>
      <script src="_scripts/script-vision/script-pagina-cadastrar-funcionarios/cadastrar-funcionarios.js"></script>



    </body>
    <!-- FIM DO BODY -->

    </html>
    <!-- FIM DO HTML -->

    <?php
	// Fechando Conexão
	
	mysqli_close($conecta);
		
?>


      <!-- ARQUIVO PHP QUE FAZ A ALTERAÇÃO DOS DADOS DO FUNCIONÁRIO incluir-funcionario.php -->


      <?php
	
	date_default_timezone_set('America/Sao_Paulo');
	require_once "../../conexao/conexao-com-banco.php";
			
	date_default_timezone_set('Etc/GMT+3');
	setlocale(LC_ALL, "", "pt_BR.utf-8");
			
			
	//PREENCHE AS VARIÁVEIS COM OS DADOS VINDOS DOS CAMPOS DO FORMULÁRIO
	
	$usuario_alterar = filter_input(INPUT_POST, 'usuario', FILTER_SANITIZE_STRING); 
	
	$funcionario_alterar = $usuario_alterar;
	
	$senha_alterar = filter_input(INPUT_POST, 'senha-usuario', FILTER_SANITIZE_STRING);

	$email_alterar = filter_input(INPUT_POST, 'email-usuario', FILTER_SANITIZE_EMAIL); 	
			
	$departamento_alterar = filter_input(INPUT_POST, 'departamento-usuario', FILTER_SANITIZE_STRING); 
	
	$empresa_origem_alterar = filter_input(INPUT_POST, 'empresa-origem-usuario', FILTER_SANITIZE_STRING);
		
	$tipo_usuario_alterar = filter_input(INPUT_POST, 'tipo-usuario', FILTER_SANITIZE_STRING); 
	
	$status_alterar = filter_input(INPUT_POST, 'status-usuario', FILTER_SANITIZE_STRING);
	
	$cod_alterar = filter_input(INPUT_POST, 'cod-funcionario', FILTER_SANITIZE_NUMBER_INT);
	
	
	if($status_alterar == "ativo")
	{
		$status_usuario_alterar = 1;
	}
	else if($status_alterar == "inativo")
	{
		$status_usuario_alterar = 0;
	}
	
			
	if($tipo_usuario_alterar == "usuariocomum")
	{
		$update_alterar_usuario = "UPDATE tbl_usuarios set funcionario = '$funcionario_alterar', usuario = '$usuario_alterar', senha = '$senha_alterar', email = '$email_alterar', DEPARTAMENTO = '$departamento_alterar', EMPRESA_ORIGEM = '$empresa_origem_alterar', USUARIO_COMUM = 1, SUPERVISOR = 0, ADMINISTRADOR = 0, ATIVO = $status_usuario_alterar, imagem = 'Sem Imagem' WHERE CODIGO = $cod_alterar";
	
	}
	
	else if($tipo_usuario_alterar == "supervisor")
	{
		$update_alterar_usuario = "UPDATE tbl_usuarios set funcionario = '$funcionario_alterar', usuario = '$usuario_alterar', senha = '$senha_alterar', email = '$email_alterar', DEPARTAMENTO = '$departamento_alterar', EMPRESA_ORIGEM = '$empresa_origem_alterar', USUARIO_COMUM = 1, SUPERVISOR = 1, ADMINISTRADOR = 0, ATIVO = $status_usuario_alterar, imagem = 'Sem Imagem' WHERE codigo = $cod_alterar";
	}
	
	else if($tipo_usuario_alterar == "administrador")
	{
		$update_alterar_usuario = "UPDATE tbl_usuarios set funcionario = '$funcionario_alterar', usuario = '$usuario_alterar', senha = '$senha_alterar', email = '$email_alterar', DEPARTAMENTO = '$departamento_alterar', EMPRESA_ORIGEM = '$empresa_origem_alterar', USUARIO_COMUM = 1, SUPERVISOR = 1, ADMINISTRADOR = 1, ATIVO = $status_usuario_alterar, imagem = 'Sem Imagem' WHERE codigo = $cod_alterar";
	}
	
	
	
	$result_update_alterar_usuario = mysqli_query($conecta, $update_alterar_usuario);
	
	$affected_rows = 0;
	$affected_rows = mysqli_affected_rows($conecta);
			

	if($affected_rows != 0)
	{	
		$select_usuarios = "SELECT * from tbl_usuarios";
		$lista_usuarios = mysqli_query($conecta, $select_usuarios);
				
		if(!$lista_usuarios)
		{
			die("Erro no Banco - Erro no Select na tabela tributações");
			exit;
		}
	
		$retorno_usuarios = array();
		while($linha_usuarios = mysqli_fetch_object($lista_usuarios))
		{					
			$retorno_usuarios[] = $linha_usuarios;					
		} 		
	}
	
	else
	{	
		die('O funcionário não foi cadastrado - Tente Novamente');
		exit();
	}
			
	echo json_encode($retorno_usuarios);	


?>

Below we have images of the system

inserir a descrição da imagem aqui

Thank you!

1 answer

0


a possible solution would be, when you click a tr, send by url some data, can be the id, code, what you think best, and when you add new, you do not send anything. example:

<button type="button"><a href="exemplo.php?id='.$id.'"><i class="fas fa-pencil-alt"></i></a></button>

In the form code you validate if there is get with the given id as in my example, if there is you put the change button if not the button is how to insert, and in the js code you implement to which ajax will send. as in the example below:

<?php
  // verifica se existe o id na url se existir ele faz a consulta no banco buscando os dados do que vai ser alterado para poder preencher o formulário
    if (isset($_GET['id'])) {
      $id = $_GET['id'];
      $sql = $pdo->prepare("exemplo..");
      $sql->execute();
      foreach ($sql as $row) {
          $exemplo1 = $row['exemplo1'];
          $exemplo2 = $row['exemplo2'];
      }
    }
    ?>

    // nos campos do fomulário você verifica se existe a variavel buscada no banco se existir vai mostrar ela no imput caso contrario ele vem vazio
    <label>exemplo1</label>
    <?php
      if (isset($exemplo1)) {        
          echo '<input type="text"  id="exemplo1" value=' . $exemplo1 . '>';
      } else {
          echo ' <inputtype="text" id="exemplo1">';
      }
    ?>

//no final do arquivo quando for ter o botão de enviar você conferi se existe o id.

<?php
  if (isset($_GET['id'])) {
    echo '<button type="button" id="btn_atualizar">Enviar</button>';
  } else {
    echo '<button type="button" id="btn_enviar">Enviar</button>';
  }
?>

Browser other questions tagged

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