如何防止同时创建具有相同详细信息的多个用户

时间:2015-03-12 20:47:20

标签: php mysql ajax duplicates

我正在尝试在PHP中创建一个注册表单,它运行正常;用户名和加密密码以及电子邮件将添加到数据库中,如果用户名或电子邮件已存在,则会通知用户他无法使用这些详细信息。然而;我有一个奇怪的错误,当我提交用户时,我的数据库中会出现两个副本。

我不确定这是怎么回事,因为JavaScript是单线程的,所以即使我要生成两个AJAX请求,第二个应该失败,因为现在用户名会有用户名吗?

如何解决这个问题?

我正在使用以下PHP文件来处理AJAX请求:

// Get our user-data:
 $username = isset( $_POST['username'] ) ? $_POST['username'] : die( "You must enter a valid username" );
 $password = isset( $_POST['pass'] ) ? $_POST['pass'] : die( "You must enter a valid password" );
 $email = isset( $_POST['email'] ) ? $_POST['email'] : "";

 try {
     $connection = new PDO( "mysql:host=$server_name;dbname=$db_name", $db_username, $db_password );
     $connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

     // Check to see if that username or password exist:
     $sql_statement = $connection->prepare( "SELECT COUNT(*) FROM users WHERE `username` = ? LIMIT 1" );
     $sql_statement->execute( array( $username ) );
     if( $sql_statement->fetchColumn() > 0 )
     {
         // That username already exists:
         die( "That username already exists" );
     }

     $sql_statement = $connection->prepare( "SELECT COUNT(*) FROM users WHERE `email` = ? LIMIT 1" );
     $sql_statement->execute( array( $email ) );
     if( $sql_statement->fetchColumn() > 0 )
     {
         // That email is already used:
         die( "There already exists an account under that email address" );
     }

     // Add the user to the database:
     $sql_statement = $connection->prepare( "INSERT INTO users( username, email, joined, password ) VALUES (?, ?, NOW(), ?)" );
     $sql_statement->execute( array( $username, $email, password_hash( $password, PASSWORD_DEFAULT ) ) );
 }
 catch( PDOException $e )
 {
     die( "There was an internal database error whilst creating your user, error code (" . $e->getCode() . ")" );
 }

1 个答案:

答案 0 :(得分:0)

  1. 您可以发帖或帖子在验证前检索数据
  2. if else语句可以消除异常
  3. 不认为你需要限制
  4. 可以使用SQL WILD CARDS
  5. 可以使用布尔值来阻止多个条目
  6. 可以将用户名,密码存储到会话或Cookie中
  7. 可以使用COUNT(电子邮件)FROM TABLE_NAME WHERE COUNT(电子邮件)> 1
  8. 可以使用echo语句进行调试