简体   繁体   English

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

[英]PHP: check row exist using mysqli query

i have this two function for create user.first function for insert/create user and other function for check if user was/exist in MySql database. 我有这两个功能来创建用户。第一个功能用于插入/创建用户和其他功能用于检查用户是否存在于MySql数据库中。 but when i send data i see blank page for die(); 但是当我发送数据时,我看到die()的空白页; (if user exsit or user not exist) how to fix this error? (如果用户已存在或用户不存在)如何解决此错误? and how to print error list in red box ie: 以及如何在红色框中打印错误列表,即:

- this user not activate 

- email is empty 

- ....

my class: 我的课:

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

This is always going to return FALSE (assuming the query successfully executes): 这总是返回FALSE (假设查询成功执行):

if ($stmt->execute()) {

    $stmt->bind_result($email);

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

You want to change it to: 您想要将其更改为:

if ($stmt->execute()) {

    $stmt->store_result();


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

}

Then, if the user is found, it will return TRUE ; 然后,如果找到该用户,它将返回TRUE if not if will return FALSE . 如果不是,则返回FALSE

Also, I think it make more sense (semantically) to have this: 另外,我认为(从语义上)具有以下含义更有意义:

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

... because you want it to return TRUE if the user is found (and end the script because you don't want to insert a duplicate)./ ...,因为您希望它在找到用户后返回TRUE (并结束脚本是因为您不想插入重复项)。/

if ($stmt->execute()) {

        $stmt->bind_result($email);

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

    return false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM