How to avoid duplicate registration in a php form

Asked

Viewed 5,783 times

2

I would like examples of how to prevent email from being duplicated if a user tries to register multiple.

 <form action="processar.php" method="POST">
      <input type="text" name="nome">
      <input type="email" name="email">
      <input type="submit">
   </form>

Process.php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "experiments";


//Pega os dados da form

   $nome = $_POST['nome'];
   $email = $_POST['email'];

 // Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection


$dupesql = "SELECT * FROM formulario where (email = '$email')";

$duperaw = mysql_query($dupesql);

if (mysql_num_rows($duberaw) > 0) {
   echo "Não deu certo, este e-mail já está cadastrado.";

} else {

$sql = "INSERT INTO formulario (nome, email)
VALUES ('$nome', '$email')";

}
  • I would do via ajax/jquery, as soon as the user finished typing something, make a query on the server by email, if already existing, warn the user. Something cool and release Submit after all the data is validated, html5o inputs, ajax/jquery, back validation. With ajax you avoid more work.

  • I recommend using mysqli or PDO since the mysql_* functions are obsolete.

3 answers

1

In select, instead of searching by name, you search by email.

$dupesql = "SELECT * FROM formulario where (email = '$email')";

You can complement this by making the primary key email in the database. This way, even if the user tries, he will not be able to register a duplicated email in your bank.

  • Error occurring: mysql_num_rows() expects Parameter 1 to be Resource, Boolean Given in line 23. :/

  • The rest of the flow stays the same. You just change that line I posted. Assign the execution of mysql_query to a variable and pass as parameter to mysql_num_rows().

  • This error is occurring in the query line... that "Where" is in minuscule letter... changes it to uppercase letter.. maybe for certain...

  • Same error keeps occurring even after changing Where to uppercase.

  • You have to look at the error log or display the error with mysql_error() to see what it is. I advise migrating to mysqli.

1

You’re creating the connection with mysqli_connect and running with mysql_query, notice the lack of i. Try to change, if it still gives error, modify your query to:

$dupesql = "SELECT * FROM formulario where email='$email'";

0

I would remove the parentheses after Where:

Variables are different. You use $duperaw and $duberaw.

Check now with the changes:

$dupesql = "SELECT email FROM formulario where email = '$email'";

$duperaw = mysql_query($dupesql);

if (mysql_num_rows($duperaw) > 0) {
//mensagem de erro //
}

else {
// continui //
}

Browser other questions tagged

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