且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP和PDO检查用户名是否存在?

更新时间:2023-11-26 09:13:58

这是因为由于范围的原因,$dbh对象仅限于try catch块和您的sql_con()函数内部.

This is because the $dbh object is limited to inside the try catch block and your sql_con() function due to scope.

正确的解决方案是删除try catch,并 sql_con()函数结束时返回$dbh变量 .

The correct solution would be to remove the try catch block, and return the $dbh variable at the end of the sql_con() function.

然后:

try {
    $dbh = sql_con();

    $stmt = $dbh->prepare("SELECT `user_login` FROM `users` WHERE `user_login` = ? LIMIT 1");
    $stmt->execute(array($username));

    if ( $stmt->rowCount() > 0 ) {
        $error[] = 'Username already taken';
    }
}
catch (PDOException $e) {

    //Do stuff with $e

}