check if data exists in the database

Asked

Viewed 56 times

0

I am learning php object oriented and wanted to know how to put if to check whether 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);
   }
?>
  • 1

    You need to be careful with those "if there is" checks. If you want to enter a new record, the correct way is to try to enter and fail if there is one, to avoid race condition. An error that I see in almost all ""home systems""" in PHP (and in some other languages, with less frequency) is the person doing the separate test of the insertion, which allows two records to be entered if they occur "almost at the same time".

1 answer

4

You must make a SELECT COUNT(*) in the database to check that 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 that doing this through functions in your model class would be something like this (in default 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 do the check:

if(verificarCPF('000.000.000-00') == 0) {
    //...
}

Browser other questions tagged

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