PHP:使用mysqli查询检查行是否存在

时间:2013-03-31 13:08:39

标签: php mysqli

我有两个函数用于创建用于插入/创建用户的user.first函数和用于检查用户是否存在于MySql数据库中的其他函数。但是当我发送数据时,我看到die()的空白页; (如果用户exsit或用户不存在)如何修复此错误?以及如何在红色框中打印错误列表,即:

- this user not activate 

- email is empty 

- ....

我的班级:

public function createUser($email, $password, $salt, $verification) {

if($this->checkUserFound($email) != true ){die();}

    $query = "INSERT INTO tbUsers (email, password, user_salt, is_verified, is_active, is_admin, verification_code) "
    . "VALUES (?, ?, ?, ?, ?, ?, ?)";

    $stmt = $this->_db->prepare($query);

    $ver = 0;
    $act = 1;
    $adm = 0;

    $stmt->bind_param("sssiiis", $email, $password, $salt, $ver, $act, $adm, $verification);

    if ($stmt->execute()) {
        return true;
    }

    return false;
}

public function checkUserFound($email) {
    $query = "SELECT email FROM tbUsers where email = ?";

    $stmt = $this->_db->prepare($query);

    $stmt->bind_param("s", $email);

    if ($stmt->execute()) {

        $stmt->bind_result($email);

        //fetch first row of results
        $stmt->fetch();
        return false;
    }

    return true;
}

2 个答案:

答案 0 :(得分:1)

这总是会返回FALSE(假设查询成功执行):

if ($stmt->execute()) {

    $stmt->bind_result($email);

    //fetch first row of results
    $stmt->fetch();
    return false;
}

您想将其更改为:

if ($stmt->execute()) {

    $stmt->store_result();


    return 0 == $stmt->num_rows ? FALSE : TRUE;

}

然后,如果找到用户,它将返回TRUE;如果不是,将返回FALSE

另外,我认为这样做更有意义(语义上):

if($this->checkUserFound($email)){die();}

...因为如果找到用户,你希望它返回TRUE(并且因为你不想插入副本而结束脚本)./

答案 1 :(得分:0)

if ($stmt->execute()) {

        $stmt->bind_result($email);

        //fetch first row of results
        $stmt->fetch();
        return true;
    }

    return false;