How to check if Cpf and cnpj already exist in the database (Pdo Php)

Asked

Viewed 649 times

-1

I’m trying to do a check when I want to register a customer. Before registering I want to check if the customer’s Cpf or cnpj already exists in the database. when I try to check only Cpf it works and returns a warning and when I try to check only cnpj, also it is right, but when I try to do for both, it returns me an error saying that the customer already exists while this informed data is not in the bank.

Here’s what I did

 //CHECKING IF THERE IS ALREADY A CNPJ OR CPF REGISTERED
  $stmt = $conn->prepare("SELECT * from rcom_clientes_clientes WHERE cnpj= ? OR cpf=?");
    $stmt -> bindValue(1 ,$cnpj);
    $stmt -> bindValue(2 ,$cpf);
    $stmt->execute(); 
    $count = $stmt->rowcount();


//IF THE CLIENT ALREADY EXIST
if( $count > 0 )
{
  echo"<script>alert('Desculpa, esse Cliente ja 
   existe!');window.location.href = '../../create_client.php';</script>";  

}
else
{
   ECHO 'DEU';
}

Somebody give me a hand there?

  • If $Cpf is empty and $cnpj is filled in with a number that does not exist in the database, it returns results that $Cpf is empty in the database. Example: $Cpf = '' and $cnpj = '001': If there is no '001' in the database, it will still return all records that 'Cpf' is empty. The most correct would be to check in PHP which variable was filled ($cnpj or $Cpf) and then query only the filled variable.

1 answer

1


There are several ways to do this, one of them is you create a function to validate any field, with this "generic" function you can take advantage to validate any single field as for example: email, username and etc.

/**
 * Função para verificar se já existe um cadastro no banco de dados
 * a partir de um campo único.
 *
 */
public function validarCampoUnico(string $field, string $value)
{
    $allowedFIelds = ['cpf', 'cnpj'];
    if (!in_array($field, $allowedFIelds)) {
        // Lançar exception ou tratar o erro da forma que você já trata seus erros da aplicação
    }

    // Caso os valores sejam armazenados no banco sem mascara
    // Isso vai remover a mascara do valor antes de enviar para o banco
    $value = preg_replace('/[^0-9]/', '', $value);

    $stmt = $conn->prepare("SELECT * from rcom_clientes_clientes WHERE {$field} = ?");
    $stmt->bindValue(1 ,$value);
    $stmt->execute(); 

    if ($stmt->rowcount() <= 0) {
        return false;
    }

    return true;
}


// Como você não informou a maneira que estava recebendo os dados,
// estou apenas dando um exemplo de utilização.
$cpf = $_POST['cpf'];

if (validarCampoUnico('cpf', $cpf)) {
    echo"<script>alert('Desculpa, esse Cliente ja 
   existe!');window.location.href = '../../create_client.php';</script>"; 
} else {
    echo 'Deu';
}

Browser other questions tagged

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