Search code examples
phpmysqlvalidationregistrationforum

PHP displaying error for already used Username and empty field


I want PHP to make sure the username is not already used and also check to see if the field is empty. Sorry I am a huge noob when it comes to php. Here is my code:

// Check for an Username:
    $dup = mysql_query("SELECT user_username FROM users WHERE user_username='".$_POST['user_username']."'");
        if(mysql_num_rows($dup) >0){
            $errors[] = 'Username already used.';
        }
        else{
            $un = mysqli_real_escape_string($dbc, trim($_POST['user_username']));
            echo '<b>Congrats, You are now Registered.</b>';
        }
        else {
            $errors[] = 'You forgot to enter your Username.';
            }

Solution

  • You have two else statements, which cannot be used. Also, you need to escape your $_POST data. Lastly, you should move away from mysql_* functions as that time has passed. Use either mysqli or PDO.

    <?php
    $sql = sprintf("SELECT user_username FROM users WHERE user_username='%s'",
            mysql_real_escape_string($_POST['user_username']));
    $dup = mysql_query($sql);
    if(empty($_POST['user_username'])){
        $errors[] = 'You forgot to enter your Username.';
    }elseif(mysql_num_rows($dup) >0){
        $errors[] = 'Username already used.';
    }else{
        $un = mysqli_real_escape_string($dbc, trim($_POST['user_username']));
        echo '<b>Congrats, You are now Registered.</b>';
    }?>
    

    An alternative, and easier flow in my opinion, would be a try/catch statement. This way you don't have to make an unnecessary database call if the username is empty:

    <?php
    try{
        if(empty($_POST['user_username'])){
            throw new Exception('You forgot to enter your Username.');
        }
    
        $sql = sprintf("SELECT user_username FROM users WHERE user_username='%s'",
            mysql_real_escape_string($_POST['user_username']));
        $dup = mysql_query($sql);
    
        if(mysql_num_rows($dup) >0){
            throw new Exception('Username already used.');
        }
    
        echo '<b>Congrats, You are now Registered.</b>';
    
    }catch(Exception $e){
        echo $e->getMessage();
    }?>