0

我正在尝试编写一种方法来检查用户是否存在并进行一些验证。

这是到目前为止的代码:

public function checkUsername(){
            if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
                $stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
                $stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
                $stmt->execute();
                if($stmt->rowCount() != 0){
                        return TRUE;
                }else{
                    return $this->error .= '<span style="color:red;">Username already exists.</span>';
                }
            }else{
                return $this->error .= '<span style="color:red;">Username must be between 3 and 15 characters.</span>';
            }

    }

这就是我试图称呼它的方式:

if( isset($_POST['register-submit'])){

        $error = '';
        $register = new register($_POST, $dbh);
            if(!$error .= $register->checkUsername()){

                    //continue

            }else{
                $error .= $register->checkUsername();
            }
    }

为了测试它,我没有在输入字段中输入任何内容来获取要返回的第一个错误并在网页上正确地回显它。但是什么都没有显示。

这是这样做的正确方法吗?抱歉,我对在类中使用方法不是很熟悉。我假设我在调用程序的初始语句中做错了什么,if我应该像我一样运行该方法两次吗?

4

1 回答 1

1

使用Exceptions. 像:

public function checkUsername(){
    if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
        $stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
        $stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
        $stmt->execute();
        if($stmt->rowCount() != 0){
                return TRUE;
        }else{
            throw new Exception("Username already exists.");
        }
    }else{
        throw new Exception("Username must be between 3 and 15 characters.");
    }

}

if( isset($_POST['register-submit'])){

    $error = '';
    $register = new register($_POST, $dbh);
    try {
        if($register->checkUsername()){
            //continue
        }
    } catch ($e) {
        $error .= '<span style="color:red;">' . $e->getMessage() . '</span>';
    }
}

您可以进行子类化,例如:

class UsernameException extends Exception {}

try {
    throw new UsernameException("Your username is too awesome");
} catch (UsernameException $e) {
    exit($e->getMessage());
} catch (SomeOtherException $e) {
    exit("500");
} catch (Exception $e) {
    exit("que?");
}
于 2013-09-16T15:31:15.690 回答