Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if username exists using PHP PDO

Tags:

php

mysql

pdo

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?
like image 844
enchance Avatar asked Nov 29 '11 18:11

enchance


People also ask

How to check if username already exists in PHP?

$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con); if (mysql_num_rows($query) != 0) { echo "Username already exists"; } else { ... }


2 Answers

Check for the row count:

if ( $sthandler->rowCount() > 0 ) {
  // do something here
}
like image 89
Tom van der Woerdt Avatar answered Sep 20 '22 10:09

Tom van der Woerdt


Just grab the row:

if( $row = $sthandler->fetch() ){
    // User exists: read its details here
}else{
    // User does not exist
}
like image 42
Álvaro González Avatar answered Sep 22 '22 10:09

Álvaro González