dongyuxiao6295 2019-07-16 22:06
浏览 180

我想检查注册页面中是否有用户名[重复]

This question already has an answer here:

I'm coding PHP system , and I want it to check if the username is available in register page. I want to avoid two users in database with same username

I tried a lot of things but didn't get it to work.

This is my 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');              
        }
    }
}
</div>
  • 写回答

1条回答 默认 最新

  • dpjw67160 2019-07-16 22:34
    关注

    You should add a new error handle, checking if the username exist in the database.

        $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
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度