5

How do I check if a username exists using PDO? All I need to know is a bool true (exists) or false (does not). I have the initial parts set up but am unsure what to do next

$sthandler = $dbhandler->prepare('SELECT username FROM userdb WHERE username=? LIMIT 1');
$sthandler->execute(array('username'));
// ... What's next?
2
  • You are gonna want to count the amount of rows that come up from the query (check tom's answer). If it's 0 the user doesn't exist, if it's 1 or more he does. One tip: I usually don't limit the query, If the username were to exist more then once I can throw an error, this means that something is bugged or a possible intruder duplicated the account... Commented Nov 29, 2011 at 18:39
  • @s4uadmin - You have to enforce certain amount of data integrity right in the database, e.g. with a unique index. Otherwise you'll get crazy testing for all the possibilities of corrupted data. Commented Nov 29, 2011 at 18:53

3 Answers 3

9

Check for the row count:

if ( $sthandler->rowCount() > 0 ) {
  // do something here
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, man. Just what I needed. Final code: if(!$sthandler->rowCount()) throw new invalidUserException();
i have a question please enlighten me for example no record exist count will be 0 0 not greater than 0 so nothing will happend should it be $sthandler->rowCount() < 1 so when a user exist it will not do anything to avoid duplicate and if none exist it will proceed?
2

Just grab the row:

if( $row = $sthandler->fetch() ){
    // User exists: read its details here
}else{
    // User does not exist
}

Comments

2
$username_exists = (bool) $sthandler->fetchColumn();

Note that you can even optimize the query a tiny bit since actually you don't need to select the username.

SELECT username FROM userdb ...

becomes

SELECT 1 FROM userdb ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.