2

I am trying to match a username in the database. If the username match it returns true otherwise it returns false.

At the moment it will always return false even when the username is correct.

Here is the class and call I'm using:

class register{
  private $result;

  public function __construct($post_data, PDO $dbh){

    $this->post_data = array_map('trim', $post_data);
    $this->dbh = $dbh;

  }

  public function checkUsername(){
    $stmt = $this->dbh->prepare("COUNT(*) FROM oopforum_users WHERE username = ?");
    $stmt->bindParam(1, $this->post_data['reg_username'], PDO::PARAM_STR);
    $stmt->execute();
    $this->result = $stmt->rowCount();
    if($this->result == 0){
        return false;
    }else{
        return true;
    }
  }

}


$register = new register($_POST, $dbh);
if($register->checkUsername()){
    //continue
}else{
    echo 'ERROR: That username is taken, please choose another one.';
}

Why is it returning false even though the username's do match?

4

1 回答 1

4

你忘了SELECT声明:

$stmt = $this->dbh->prepare("SELECT COUNT(*) FROM oopforum_users WHERE username = ?");

除此之外,您的查询将始终返回一行(正好是 1 行),但该行的内容可能包含 0 作为行数,因此您需要更改逻辑:选择一个真实列而不是COUNT(*)使用$stmt->rowCount()或读取计数的值并检查。

于 2012-07-03T15:25:09.140 回答