check if data exists in the database

0

I'm learning object-oriented php and wanted to know how to put if to check if data already exists in the database

<?php

  include "head.php";
  if(isset($_POST['email'])){

     include 'class/classEmpresa.php';
     $empresa = new empresa();
     $verificacnpj = $empresa->verificaCnpjExiste($_POST['cnpj'],$conectaBanco);
     $id_empresa = $empresa->cadastraEmpresa($_POST['nome_fantasia'],$_POST['cnpj'],$_POST['telefone'],$_POST['email'],$conectaBanco);

     include 'class/classPessoa.php';
     $pessoa = new pessoa();
     $verificacpf = $pessoa->verificaCpfExiste($_POST['cpf'],$conectaBanco);
     $id_pessoa = $pessoa ->cadastraPessoa($_POST['nome'],$_POST['cpf'],$_POST['email'],$_POST['telefone'],$id_empresa,$conectaBanco);

     include 'class/classUsuario.php';
     $usuario = new usuario();
     $verificaEmail = $usuario->verificaEmailExiste($_POST['email'],$conectaBanco);
     $cadastraUsuario = $usuario ->cadastraUsuario($_POST['email'],$_POST['senha'],$id_pessoa,$conectaBanco);     

     include 'class/classHtml.php';
     $msg = new html();
     $mostrar = $msg->mostrarScript('cadastrado com sucesso!');
     echo ($mostrar);
   }
?>
    
asked by anonymous 18.03.2018 / 19:03

1 answer

4

You should make a SELECT COUNT(*) in the database to check how many users have that field, for example:

SELECT COUNT(*) FROM pessoa WHERE cpf = $cpf;

This will return how many people have the specified cpf.

In case I believe you're doing this through functions in your model class it would look something like this (in the standard STMT ):

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

function verificarCPF($cpf) {
    $stmt = $mysqli->prepare("SELECT COUNT(*) FROM pessoa WHERE cpf = ?;");
    $stmt->bindParam("s", $cpf);
    $stmt->execute();
    $result = $stmt->get_result();

    return $result->fetch_array()[0];
}

Then just check it out:

if(verificarCPF('000.000.000-00') == 0) {
    //...
}
    
18.03.2018 / 19:28