我正在尝试在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() . ")" );
}
答案 0 :(得分:0)