MySQLi num_rows returns 0

前端 未结 3 1461
北荒
北荒 2020-12-22 07:28

Here\'s my code

$stmt = $conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare(\'SELECT Username, EmailVerified, Blocked FROM user WHERE Emai         


        
相关标签:
3条回答
  • 2020-12-22 07:56

    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';
    }
    
    0 讨论(0)
  • 2020-12-22 07:57

    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){
      ...
    }
    
    0 讨论(0)
  • 2020-12-22 08:00

    To fix your problem remove this line:

    $stmt->store_result();
    

    The problem is that you used two methods which are in conflict with each other.

    $stmt->store_result();
    $result = $stmt->get_result();
    

    Both of these methods fetch the results. store_result() fetches the results internally and stores them in the statement object. I would advise to avoid this method whenever possible. It is difficult to use. get_result() fetches the results and saves them in a separate object. Once the results are fetched from MySQL, they cannot be fetched again. Use only one of these methods at a time.

    In your case you first stored the results in mysqli_stmt and then fetched an empty result set into $result. $result will contain 0 rows, because all of the records have already been stored in the statement. To get the number of rows stored there use $stmt->num_rows.

    Both mysqli_stmt and mysqli_result classes have the num_rows property. The key is to use the appropriate one.

    0 讨论(0)
提交回复
热议问题