Prohibit the insertion of repeated data

2

I need to type a text in an input on the form, it validates there even if this record already exists, that shows the result to the user and that does not allow to send the form without changing what is repeated.

form and js:

<form role="form" method="POST" action="php/cadastro.php" accept-charset="utf-8">
  <div class="form-group">
    <label for="exampleInputPassword1">Descrição</label>
    <input type="text" class="form-control" name="descricao" id="descricao" required="required">
  </div>
</form>

    <script type="text/javascript">
    $(function(){ 
      $("input[name='descricao']").on('exit', function(){
        var descricao = $(this).val();
        $.get('arquivo.php?descricao=' + descricao, function(data){ 
          $('#resultado').html(data);
        });
      });
    });
    </script>

file.php

<?php
  $conexao   = mysqli_connect('', '', '', ''); 
  $descricao = filter_input(INPUT_GET, 'descricao');
  $sql       = "SELECT * FROM tabela WHERE descricao = '{$descricao}'";
  $query     = $mysqli->query( $sql ); 
  if( $query->num_rows > 0 ) {
    echo 'Já existe!';
  } else {
    echo 'Não existe ainda!';
  }
?> 

I would like it not to be a verification file, to verify with php in the form itself and to show the user already that he can not use such a description, without having to go to another file to search the registry and return to the page.

file upload to bank:

$conexao          = mysqli_connect('', '', '', '');
$descricao        = $_POST['descricao'];

$sql            = "INSERT INTO tabela(descricao) VALUES ('$descricao')";

If anyone has suggestions, thank you.

    
asked by anonymous 12.04.2017 / 17:49

1 answer

1

A very simple way to implement this behavior would be to use listeners on input and running a query via ajax to the server to validate the description data. You can have a page with the following code:

<html>
    <head>
        <style type="text/css">
            .message {
                display: none;
            }
        </style>
    </head>
    <body>
        <form role="form" method="POST" action="cadastro.php" accept-charset="utf-8">
            <div class="form-group">
                <label for="descricao">Descrição</label>
                <input type="text" class="form-control" name="descricao" id="descricao" required="required">
                <br/>
                <span class="message"></span>
            </div>
        </form>
        <script
            src="https://code.jquery.com/jquery-3.2.1.js"integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
        crossorigin="anonymous"></script>
        <script type="text/javascript">
                $('#descricao').on('change paste keyup', function () {
                    var messageSpan = $('.message');
                    $.get({
                        url: '/valida_descricao.php',
                        data: {'descricao': $(this).val()}
                    }).done(function () {
                        messageSpan.text('Descrição aceita!');
                        messageSpan.css('display', 'inline');
                    }).fail(function () {
                        messageSpan.text('Descrição não aceita!');
                        messageSpan.css('display', 'inline');
                    });
                });
        </script>     
    </body>
</html>

... and a php script called valida_descricao.php for validation:

<?php
// Obtendo o valor da variável
$descricao = filter_input(INPUT_GET, 'descricao');

// Conectando ao banco de dados
$conexao = mysqli_connect('localhost', 'username', 'password', 'test');
$sql = "SELECT * FROM tabela WHERE descricao = '{$descricao}'";
$query = $conexao->query($sql);
if ($query->num_rows > 0 || empty($descricao)) {
        // Define HTTP Status Code para 403 (HTTP/1.1 403 Forbidden)
        http_response_code(403);
} else {
        // Define HTTP Status Code para 200 (HTTP/1.1 200 OK)
        http_response_code(200);
}

The flow of the javascript code at the bottom of the page will be controlled according to the HTTP Status Code defined in the server response. And that's it.

Some of the concepts, techniques, and tools used in this implementation: Ajax ; HTTP Status Code ; EventTarget .

    
26.05.2017 / 07:58