The following receives a proposed username, and returns the username if not used, or the username appended by the smallest integer if used. It works fine, but I just can't help wondering if it could be done just as well with a single method. What's got me stumped is the WHILE statement requires both $stmt->execute(...)
and return $stmt->fetchColumn()
as the conditional. I guess an anonymous function would work, but don't think this will allow the prepared statement to be used for each call. I am thinking a DO loop might work, but I don't have much experience with them and reading http://www.php.net/manual/en/control-structures.do.while.php implies I should "use goto operator instead of this hack." Please provide recommended way of doing this. Thanks
<?php
class myClass
{
public function createUsername($name)
{
$i='';
while($this->openUsername($name.$i)==FALSE){$i=$i+1;}
return $name.$i;
}
private function openUsername($name)
{
$sql='SELECT id FROM users WHERE username=?';
try
{
$stmt = db::db()->prepare($sql);
$stmt->execute(array($name));
return $stmt->fetchColumn()?FALSE:TRUE;
}
catch(PDOException $e){die(library::sql_error($e,$sql));}
}
}
?>