mysqli prepared statement num_rows function

2020-04-12 07:01发布

So it is my first day working in MYSQLi(converting over from mysql), and I am having trouble with my login script where I check for duplicate emails:

Here is what i've got:

$email = mysqli_escape_string($_POST['email']);

$stmt=$mysqli->prepare("SELECT username from users WHERE email=?");
$stmt->bind_param('s',$email);
$stmt->execute(); 
$nrows1=$mysqli->num_rows;
echo $nrows1;
$stmt->close();

if ($nrows1>0) {
    $_SESSION['loggedin'] = false;
    $_SESSION['error'] = "Our records indicate that there is already an account registered with that email. Please use the 'forgot your password' link below if you cannot remember your password.";
    header('Location: registration.php');
    echo "running insisde duplicate email";
        exit();
}

I keep returning 0 rows or an empty variable when echoing $nrows1. When I enter the query directly in sql, it works fine. I seem to be following the documents and have tinkered a bunch with it.

I also used the affected rows function, but I do not believe that is appropriate for a SELECT statement, correct?

Sincere thanks for any help, it is greatly appreciated.

标签: php mysql mysqli
1条回答
虎瘦雄心在
2楼-- · 2020-04-12 07:53

After executing, you need to use mysqli_stmt_store_result() to get the result set, so it will know how many rows there are. Also, you should apply $num_rows to the statement, not the connection.

$stmt->execute();
$stmt->store_result();
$nrows1 = $stmt->num_rows;
查看更多
登录 后发表回答