0

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));}
        }

    }
?>
4

2 回答 2

0

我个人会这样做:

function createUsername($name) {
    // validate $name, for instance restrict to alphanumeric characters with preg_match
    $sql = "SELECT GREATEST(`username`) AS `out` FROM `users` 
         WHERE `username` REGEXP '^".$name."\d*$'";
    $result = // whatever code it takes for PDO to run the above query
    if( !$result) return $name; // nobody with that name yet
    $number = preg_replace("^.*(\d*)$","$1",$result['out']);
    if( !$number) return $name."1";
    return $name.($number+1);
}
于 2013-02-09T22:44:12.517 回答
0

不知道这是否可行,如果您认为这不是一个好方法,请投反对票(但请评论原因)。谢谢

public function createUsername($name)
{
    try
    {
        $i='';
        $sql='SELECT id FROM users WHERE username=?';
        $stmt = db::db()->prepare($sql);
        do {
            $stmt->execute(array($name.$i));
            $used=$stmt->fetchColumn()?TRUE:FALSE;
            if(!$used) {$i=$i+1;}
        } while ($used);
    }
    catch(PDOException $e){die(library::sql_error($e,$sql));}
    return $name.$i;
}
于 2013-02-09T23:17:54.597 回答