JDelage
JDelage

Reputation: 13672

PDO - get the result of a COUNT(*)?

During the new user registration process, I'm trying to find whether a user name or a user email are already in the db. To do that, I want to find the number of rows where the identifier (email or user name) matches records in the database. If I don't screw up, the only possible return values are 0 or 1. My function is below, but I need help to complete it.

function checkUserExists($userIdentifier, $tableColName){
 $dbConnection=$this->dbInstance->createConnexion();
 $query=$dbConnection->prepare("SELECT count(*) FROM users WHERE ".$tableColName."= :userIdentifier");
 $query->bindParam(":userIdentifier", $userIdentifier);
 $result=$query->execute();
 if( ????? >0){
  $return false;
 } else return true;
}

Silly of me, I'm not sure how to get that count number. I suppose it's some variation of $query->fetch(), but that's going to be an array right?

Upvotes: 4

Views: 2061

Answers (2)

sholsinger
sholsinger

Reputation: 3088

You could use ->fetchColumn(0) to get the 1 and only column from the next (one and only) rowset.

if ( $query->fetchColumn(0) > 0 ){
  return false;
} else return true;

Upvotes: 3

Powerlord
Powerlord

Reputation: 88796

(Note: I haven't tested this, nor do I have PHP installed on my work machine to test it; I work in a C#/Java shop)

Likely, you'd want $query->fetchColumn();

You can also pass which column number you want, but it defaults to column 0.

Upvotes: 7

Related Questions