MySQLi num_rows returns 0

2019-03-03 22:26发布

问题:

Here's my code

$stmt = $conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare('SELECT Username, EmailVerified, Blocked FROM user WHERE Email = ? AND SLANumber = ? AND Password = ?');
$stmt->bind_param('ssb', $_POST['EmailID'], $_POST['SLANumber'], $_POST['Password']);
$stmt->execute();
$stmt->store_result();
$result = $stmt->get_result();
if($result->num_rows == 0){
    echo 'No rows found';
}
else{
    // Continue processing here
    .....
}

The code always echoes No rows found. A day or two before, it was working fine.

As expected, running the query directly gives the desired result.

What's wrong with the code?

回答1:

num_rows is a property of mysqli_stmt, not of a result resource. So you should be doing:

$result = $stmt->get_result();

// Also check strict comparison against int 0,
// to avoid incorrect equality with boolean FALSE
if($stmt->num_rows === 0){
    echo 'No rows found';
}


回答2:

Don't use store_result and get_result together in the same statement.

Use store_result method with "num_rows", "bind_result" and "fetch".

For get_result method, use "affected_rows" and "fetch_array". You can still use the "num_rows" property in the income get_result method as shown below.

$stmt->execute();
// $stmt->store_result();
$result = $stmt->get_result();
if(result->num_rows == 0){
  ...
}

OR

$stmt->execute();
// $stmt->store_result();
$result = $stmt->get_result();
if($stmt->affected_rows == 0){
  ...
}


标签: php mysqli