Avoid Duplication in the PHP + MySQLi Registry

2

Good evening!

How do I prevent registration with the same information?

Currently my "processa.php" is this way, and I wanted to include the function mentioned above ...

<?php

session_start();
include_once ("conexao.php");

$nome = filter_input($INPUT_POST, 'nome', FILTER_SANITIZE_STRING);
$email = filter_input($INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$senha = filter_input($INPUT_POST, 'senha', FILTER_SANITIZE_STRING);
$cargo = filter_input($INPUT_POST, 'cargo', FILTER_SANITIZE_STRING);
$setor = filter_input($INPUT_POST, 'setor', FILTER_SANITIZE_STRING);

$result_usuario = "INSERT INTO usuarios (nome, email, senha, cargo, setor, created) VALUES ('$nome', '$email', '$senha', '$cargo', '$setor', NOW())";
$resultado_usuario = mysqli_query($conn, $result_usuario);

if(mysqli_insert_id($conn)){
    $_SESSION['msg'] = "<p style='color:green;'>Usuário cadastrado com sucesso</p>";
    header("Location: cadastrar-usuario.php");
}else{
    $_SESSION['msg'] = "<p style='color:red;'>Usuário não foi cadastrado com sucesso</p>";
    header("Location: cadastrar-usuario.php");
}


?>
    
asked by anonymous 03.09.2018 / 00:21

1 answer

1

If you want a column to be unique, use the unique constrain . Just that, that's all.

create table pessoas (
    id int not null auto_increment,
    nome varchar(255),
    email varchar(255) unique
);
  

In this example, the email column will be unique, while the nome column may be repeated.

In this way, whenever you make a INSERT of an email that already exists, the database will return an error. Treat this error as needed.

Make SELECT before INSERT to check whether or not the registry is gambiarra - not to mention that it is subject to race conditions: email can be registered between executions of SELECT and INSERT , getting duplicate the same way.

    
03.09.2018 / 19:01