php - 我想检查用户名在注册页面是否可用

标签 php mysql

我正在编写 PHP 系统,我希望它检查用户名在注册页面中是否可用。我想避免数据库中的两个用户具有相同的用户名

我尝试了很多方法,但没有成功。

这是我的 config.php:

// REGISTER USER
function register(){
// call these variables with the global keyword to make them available in 
    function
    global $db, $errors, $username;

    // receive all input values from the form. Call the e() function
    // defined below to escape form values
    $username    =  e($_POST['username']);
    $password_1  =  e($_POST['password_1']);
    $password_2  =  e($_POST['password_2']);

    // form validation: ensure that the form is correctly filled
    if (empty($username)) { 
        array_push($errors, "Username is required"); 
    }
    if (empty($password_1)) { 
        array_push($errors, "Password is required"); 
    }
    if ($password_1 != $password_2) {
        array_push($errors, "The two passwords do not match");
    }

    // register user if there are no errors in the form
    if (count($errors) == 0) {
        $password = md5($password_1);//encrypt the password before saving in the database

        if (isset($_POST['user_type'])) {
            $user_type = e($_POST['user_type']);
            $query = "INSERT INTO users (username, user_type, password) 
                      VALUES('$username', '$user_type', '$password')";
            mysqli_query($db, $query);
            $_SESSION['success']  = "New user successfully created!!";
            header('location: dashboard.php');
        }else{
            $query = "INSERT INTO users (username, user_type, password) 
                      VALUES('$username', 'user', '$password')";
            mysqli_query($db, $query);

            // get id of the created user
            $logged_in_user_id = mysqli_insert_id($db);

            $_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
            $_SESSION['success']  = "You are now logged in";
            header('location: dashboard.php');              
        }
    }
}

最佳答案

您应该添加一个新的错误句柄,检查数据库中是否存在该用户名。

    $query="SELECT COUNT(username) as counter FROM users WHERE username='$username'";
    $checkusername=mysqli_query($db, $query);
    if($checkusername[0]->counter){
        array_push($errors, "The username is already taken");

    }

//Here your insert logic

关于php - 我想检查用户名在注册页面是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066059/

相关文章:

php - Zend组织问题

php 用户 ID 分配不起作用

php - CakePHP 3.0 中 add 方法中将附加数据保存到 Join 表

mysql - 使用联合左连接和内连接优化查询

php - 用于股票系统的EAV模型方案还是其他方法?

php - 如何计算列中相同结果的数量?

php - 如何从 Slim 3 php 框架访问所有路由?

如果检测到暴力尝试,PHP 使用 reCAPTCHA

php - php中mysql的左连接/外键问题

java - 我需要了解如何从数据库中获取唯一的随机行