Avoid duplicity in INSERT with PHP

Asked

Viewed 210 times

1

I’m trying to make my registration avoid entering the same information more than once, registration occurs from a modal like this below:

inserir a descrição da imagem aqui

After filling in the information, the data is submitted to an AJAX, like this one below:

function add_ionix(idOcorrencia,idTipoIonix,ionix,sas,idUsuario){

    $.ajax({
        url: "add_ionix.php",
        type: "POST",

        data: {
                id_ocorrencia: idOcorrencia,
                id_tipo_ionix: idTipoIonix,
                ionix: ionix,
                sas: sas,
                id_usuario: idUsuario,
        }

        }).done(function(data){

            //$("#formIonixAjax").html(data);
                alert("Ionix adicionado com sucesso!");
                $("#txt_ionix_preventivo").val("");
                $("#txt_ionix_ocorrencia").val("");
                $("#txt_sas").val("");
        });
    }

It works perfect the data passage, but at the time of entering, I’m trying to bar the same registration more than once, when I click on Add Modal closes and does not register, one hour change the script and register, but is not validating the message "Existing registration", could someone help me with the example below:

<?php 
include_once("config/conexao.php");

$idocorrencia   = $_POST['id_ocorrencia'];
$idtipoionix    = $_POST['id_tipo_ionix'];
$ionix          = $_POST['ionix'];
$sas            = $_POST['sas'];
$idusuario      = $_POST['id_usuario'];

    //$consulta = ("[LISTA].[SP_IONIX]);
    $consulta = mssql_query("SELECT * FROM TBL_IONIX WHERE IONIX = '"$ionix"' OR SAS = '"$sas"' ");

    $resultado = mssql_num_rows($consulta);

    if($resultado >= 1){
            echo "<script type=\"text/javascript\">alert(\"Este registro já existe\");</script>";
        }else{
            $sql = mssql_query("[INSERIR].[SP_IONIX] $idocorrencia, $idtipoionix ,$ionix,$sas, $idusuario");
    }
?>

I’m not understanding the reason not to fall into the IF conditions, thanks already

  • paste the code Select and click code sample in the editing tools to become more understandable

  • Thank you, but the rest of the doubt was missing.

  • not this falling in if by condition is false, ie this searching for nothing in the bank, I recommend you compare the condition Where with the data coming from the form with the inserted in the database, for example it may be that a white space is already giving difference in the condition..

1 answer

0

I do not know if it is the optimized way, but you could also do a foreach before performing the inclusion, when the user click the add button, see this example

// Verificando e Já existe algum Produto de mesmo nome cadastrado, para evitar duplicidade.

    // Instanciando a Classe e armazenando o resultado na variavel $Result      
    $result = $objeto->ProdutoConsulta();

          foreach($result as $dados_dupl =>$key){
            $duplicidade = $key->nome_produto;
            $duplicidade_id = (int) $key->id_produto;

              if ($duplicidade == $nome_produto){

                  if ($duplicidade_id <> $id_produto[0]){

                    echo" <div class='alert alert-danger text-center' id='mensagem'role='alert'>";
                    // chamando a funcao responsável pelo alerta
                    echo $msg->msgerroduplicidadeproduto();
                    echo"</div>";
                    exit();

                  } // fim do if 

              } // fim do if

          } // fim do foreach

There I basically check the data, if it locates the record with the same name I check if the id is the same.. if it is.. it comes out of the loop and stops with Exit, I do it before the Insert

  • Guys, I managed to resolve the issue, in SELECT itself I left it as SELECT * FROM TBL_IONIX WHERE IONIX = $ionix OR SAS = $sas "because before it was as SELECT * FROM TBL_IONIX WHERE IONIX = '"$ionix"' OR SAS = '"$sas"' ", with quotes in the fields of the tables, thanks again for the aid.

Browser other questions tagged

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