Checking whether the record already exists in the database [duplicate]

-1

I'm using this function in my form but I have a problem.

It is validating the field and is not including in the bd, but the message instead of saying that the client already exists is saying that it was successfully registered.

How to fix this? ... if it already exists in BD it informs that the client already exists and if it does not exist it informs that it has been registered?

My code looks like this:

$search = mysql_query("SELECT * FROM clientes WHERE cnpj = '$cnpj'");
if(@mysql_num_rows($search) > 0){
echo 'Esse Cliente já existe';
}else
// faz inserção

     mysql_query("INSERT INTO clientes (dia,mes,ano,data2,nome,fantasia,contato,fone,celular,email,cnpj,estadual,endereco,cep,bairro,cidade,estado,nf,desconto,obs) values
                                       ('$dia','$mes','$ano','$data2','$nome','$fantasia','$contato','$fone','$celular','$email','$cnpj','$estadual','$endereco','$cep','$bairro','$cidade','$estado','$nf','$desconto','$obs')");
   }
}

echo '<script type="text/javascript">
             alert("Registro Incluído com Sucesso!!!"); 
    </script>';

//Atualize a página
echo
'<script type="text/javascript">location.replace("clientes.php");</script>';
    
asked by anonymous 20.12.2017 / 15:21

2 answers

0
$search = mysql_query("SELECT * FROM clientes WHERE cnpj = '$cnpj'");
if(@mysql_num_rows($search) > 0){
    echo '
        <script type="text/javascript">
             alert("Esse Cliente já existe"); 
        </script>
    ';
}else{

    // faz inserção

     mysql_query("INSERT INTO clientes (dia,mes,ano,data2,nome,fantasia,contato,fone,celular,email,cnpj,estadual,endereco,cep,bairro,cidade,estado,nf,desconto,obs) values('$dia','$mes','$ano','$data2','$nome','$fantasia','$contato','$fone','$celular','$email','$cnpj','$estadual','$endereco','$cep','$bairro','$cidade','$estado','$nf','$desconto','$obs')");

    echo '
        <script type="text/javascript">
            alert("Registro Incluído com Sucesso!!!"); 
        </script>
    ';
}

//Atualize a página
echo '<script type="text/javascript">location.replace("clientes.php");</script>';
    
20.12.2017 / 16:14
0

The section where you tell the success of the inclusion must be inside the else block. In the code of the question this excerpt is outside the else, so it always shows the message.

    
20.12.2017 / 16:23