Check if this is duplicate

后端 未结 4 602
梦谈多话
梦谈多话 2021-01-29 08:14

I want to check if the username already exists and throw an error message if exist, any tips how can I do it? I\'ve already tried to search but only found mys

相关标签:
4条回答
  • 2021-01-29 08:53

    Two solutions:

    You could make the username field unique, this way, MYSQL would throw an error if you try to insert a line with an existing username.

    $sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
    $q = $pdo->prepare($sql);
    $result = $q->execute(array($username,$password,$role));
    if(!$result) {
        // print out your error message
    }
    

    Otherwise, make a select with the wanted username and see if a row is returned (= already used) or not (=available).

    $sql = "SELECT COUNT(*) as count FROM users WHERE username = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($username));
    $result = $q->fetchAll();
    // test result, if 1 > print error, etc
    
    0 讨论(0)
  • 2021-01-29 08:57
     <?php
         $getUniqueUsername=$con->query("select * from user where name='$user_name");
         $rowCount=$getUniqueUsername->num_rows;
    
         if($rowCount) {          
              $insertQuery=$con->query("insert into table_name (field_name) Values('".$values."'));
         }
    ?>
    
    0 讨论(0)
  • 2021-01-29 09:09
    SELECT * FROM users WHERE username = $username
    

    If found show error, else insert

    0 讨论(0)
  • 2021-01-29 09:11

    If you want to check if the username is already used :

    SELECT * FROM users WHERE username = :username
    

    If you return one row : you throw your error, else you do your INSERT

    So your code should look like this :

    if ($valid) {
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $sql_check = "SELECT * FROM users WHERE username = :username";
        $test = $pdo->prepare($sql_check);
        $test->bindParam(':username', $username); 
        $test->execute;
    

    Now here is two solution to check if you have one row :

        if($test->rowCount() > 0) {
            // error
        }      
    

    or

        $user = $test->fetch();
    
        if (!empty($user)) {
            // error
        }
    

    And now if you don't have error, do you insert :

        else {
            //$password = md5($password);
            $sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
            $q = $pdo->prepare($sql);
            $q->execute(array($username,$password,$role));
            Database::disconnect();
            header("Location: index.php");
        }
    }
    
    0 讨论(0)
提交回复
热议问题