PHP - Duplicate code or dual use a function for user authentification
<p>All,</p>

<p>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).</p>

<p>Currently, I re-use the function below, which is mostly used to <strong>retrieve</strong> a user, based on the user name, during the login process:</p>

<pre><code>function retrieveUserByUserName($userName){
 $dbConnection=$this-&gt;dbInstance-&gt;createConnexion();
 $query=$dbConnection-&gt;prepare("SELECT * FROM users WHERE userName= :userName");
 $query-&gt;bindParam(":userName", $userName);
 $query-&gt;execute();
 $result=$query-&gt;fetchObject('userName');
 if ($result){
  return $result;
 } else {
  return false;
 }
}
</code></pre>

<p>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:</p>

<pre><code>function checkUserName($userName){
  $dbConnection=$this-&gt;dbInstance-&gt;createConnexion();
  $query=$dbConnection-&gt;prepare("SELECT * FROM users WHERE userName= :userName");
  $query-&gt;bindParam(":userName", $userName);
  $result=$query-&gt;execute();
  return $result;
}
</code></pre>

<p>This makes the code slightly heavier.</p>

<p>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?</p>

<p>Many thanks,</p>

<p>JDelage</p>

<p>PS: I'm pretty new at all that, sorry for the very basic question.</p>

<p>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 <code>$result</code> is always <code>true</code>, right?</p>
