-2

I want to check the username to contain only letters. If it doesn't contain any letters, the registration I want to fail. Is it good to use preg_match? Now if I input for username: a1, also filling the password, confirm password and type fields the registration is successful.

form.php

if (isset($_POST['submit'])){


    /* if the username is alphabetic */

    if (ctype_alpha(str_replace(' ', '', $username)) === false &&!empty($username) ) {
        $errors[] = 'Userame must contain letters and spaces only';
    }

    /* if passwords match */
    if((!empty($password) && !empty($repassword)) && ($password != $repassword)){
        echo "Passwords do not match.";
    }



    if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['type'])){


            $sql = "INSERT INTO users (username, password, type) VALUES ('$username', '$password', '$type')";

            $result = mysql_query($sql);

            echo 'Successful Registration.';
    }
    else{
        echo 'Please fill all the fields.';
    }

} 
JackDog
  • 35
  • 9
  • Why do you want to limit this? – Jay Blanchard May 06 '15 at 18:16
  • Because the username must be only with letters – JackDog May 06 '15 at 18:18
  • while your filtering kinda-sorta-maybe "fixes" the problem, you are still coding in a way that is vulnerable to [sql injection attacks](http://bobby-tables.com), and your code blindly assumes queries can never fail. bad bad bad assumption. – Marc B May 06 '15 at 18:19
  • Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and consider using [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 06 '15 at 18:20
  • Why must it be only letters? – Jay Blanchard May 06 '15 at 18:20
  • There must be thousands of scripts out there. You don't need us, *do they Sam?* - @JayBlanchard – Funk Forty Niner May 06 '15 at 18:25
  • *Nah Ralph*, we certainly aren't needed here @Fred-ii- – Jay Blanchard May 06 '15 at 18:39
  • The OP's got something to chew on below *Sam* - @JayBlanchard if that doesn't get their fancy, nothing will. – Funk Forty Niner May 06 '15 at 18:40

1 Answers1

1

If you're looking for just letters in the username, preg_match will work for you.

For example,

if(!preg_match("/^[a-zA-Z]+$/", $username)){
    // if the username has non-letter characters
}

However, like the comments are saying, there are much better ways to approach preventing SQL injection attacks. Switching to prepared statements is a great start.