Avoid Duplicity in PHP+Mysqli Registration

Asked

Viewed 218 times

2

good night!

How do I prevent registration with the same information?

Currently my "processa.php" is like this, 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");
}


?>
  • 1

    I think that before you should define what would be unique (name, email), usually set the email as unique, because other information may vary. Then you check if the email already exists as a condition to register or not.

1 answer

1

If you want a column to be unique, use the Unique constrain. Just that, just that.

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

In this example, the column email will be unique, while the column nome can repeat.

This way, whenever you make one INSERT of an existing email, the database will return an error. Treat this error as your need.

Do SELECT before the INSERT to check whether or not the registration is gambiarra - not to mention that it is subject to racing conditions: the email can be registered between the executions of the SELECT and of INSERT, being duplicated in the same way.

Browser other questions tagged

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