Check if username exists with PHP PDO

How to check if username exists using PDO? All I need to know is bool true (exists) or false (not). I have the initial parts, but I'm not sure what to do next

$sthandler = $dbhandler->prepare('SELECT username FROM userdb WHERE username=? LIMIT 1');
$sthandler->execute(array('username'));
// ... What next?
+5
source share
3 answers

Check the number of lines:

if ( $sthandler->rowCount() > 0 ) {
  // do something here
}
+9
source

Just take the line:

if( $row = $sthandler->fetch() ){
    // User exists: read its details here
}else{
    // User does not exist
}
+2
source
$username_exists = (bool) $sthandler->fetchColumn();

Please note that you can even optimize the query a little, since in fact you do not need to choose a username.

SELECT username FROM userdb ...

becomes

SELECT 1 FROM userdb ...
+2
source

All Articles