All,
I am building a small, non-commercial consumer website. During the user registry, I want to check whether their chosen user name already exist in my user db (MySQL).
Currently, I re-use the function below, which is mostly used to retrieve a user, based on the user name, during the login process:
function retrieveUserByUserName($userName){
$dbConnection=$this->dbInstance->createConnexion();
$query=$dbConnection->prepare("SELECT * FROM users WHERE userName= :userName");
$query->bindParam(":userName", $userName);
$query->execute();
$result=$query->fetchObject('userName');
if ($result){
return $result;
} else {
return false;
}
}
This is slightly overengineered just to test whether the user name exists, but my main concern is that it returns the full user object, which might be unsafe and is certainly somewhat wasteful. My alternative would be to create a dedicated function:
function checkUserName($userName){
$dbConnection=$this->dbInstance->createConnexion();
$query=$dbConnection->prepare("SELECT * FROM users WHERE userName= :userName");
$query->bindParam(":userName", $userName);
$result=$query->execute();
return $result;
}
This makes the code slightly heavier.
So my question to the SO community is: what is the right tradeoff? Duplicate code or use a function for a secondary purpose? Is there a good rule of thumb for that kind of question, or does it depend?
Many thanks,
JDelage
PS: I'm pretty new at all that, sorry for the very basic question.
PPS: I'm now wondering whether the 2nd query would ever do what I want. If there are no records in the db with those parameters, the query still executes and the value of $result
is always true
, right?