Skip to content
Advertisement

how can i restrict a person from entering a particular username in username field?

I want to block a certain word from being entered in my username field.

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "s", $param_username);
        
        
        $param_username = trim($_POST["username"]);
        
     
        if(mysqli_stmt_execute($stmt)){
            /* store result */
            mysqli_stmt_store_result($stmt);
            
            **if(mysqli_stmt_num_rows($stmt) == 1) {
                *$username_err = "This username is already taken.";*
            } else{
                $username = trim($_POST["username"]);
            }**

I want to add another condition where I want to block a specific username and show an echo for it.

        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }

        
       

Advertisement

Answer

If you want to compare more than one value.

Try this code.

<?php
$reservedUsername = array('saurishmonga','users','friends','settings','logout','blahblah'));

$param_username = trim($_POST["username"]);
if (!in_array(strtolower($param_username), strtolower($reservedUsername))
{
    // insert user in the darabase
    if ($stmt = mysqli_prepare($link, $sql)) {

        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "s", $param_username);            
    
        if (mysqli_stmt_execute($stmt)) {
            // store result
            mysqli_stmt_store_result($stmt);
            
            if(mysqli_stmt_num_rows($stmt) == 1) {
                $username_err = "This username is already taken.";*
            }
            else{
                $username = $param_username;
            }
        }
        else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }
}
    else {
        echo "You can't use a reserved username";
    }

?>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement