在mysqli_stmt_execute之后不能使用PHP - mysqli_num_rows?

时间:2014-02-08 02:23:08

标签: php mysqli

我正在使用预准备语句,并希望计算查询结果集的行号:

        /* create a prepared statement */  
        // Note: mysqli can only use placeholder ? in prepared statement!
        $q = "SELECT user_id, first_name, DATE_FORMAT(last_login_time, '%a, %b %e at %l:%i%p') as f_last_login_time, last_login_time FROM users WHERE (email=? AND pass=SHA1(?)) AND active IS NULL";                
        $stmt = mysqli_prepare($dbc, $q);  

        /* bind parameters for markers */
        mysqli_stmt_bind_param($stmt, "ss", $e, $p);

        /* execute query */
       $r =  mysqli_stmt_execute($stmt);


       if (mysqli_num_rows($r) == 1) { // A match was made in the user table

                /* bind result variables */
                mysqli_stmt_bind_result($stmt, $user_id, $first_name, $f_last_login_time, $last_login_time);

                /* fetch value */
                // Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result(). 
                mysqli_stmt_fetch($stmt); 

此处if (mysqli_num_rows($r) == 1)错误:mysqli_num_rows() expects parameter 1 to be mysqli_result, object given.

我检查了手册:

  

程序样式int mysqli_num_rows(mysqli_result $ result)

     

返回结果集中的行数。

     

mysqli_num_rows()的行为取决于是缓冲还是缓冲   正在使用无缓冲的结果集。对于无缓冲的结果集,   mysqli_num_rows()将不会返回正确的行数   结果中的行已被检索。参数¶

     

结果

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

那么如果我使用Mysqli预处理语句(程序样式),如何计算结果集的行号?

1 个答案:

答案 0 :(得分:4)

mysqli_stmt_execute返回一个布尔值,指示查询是否成功,它不返回mysqli_result。您需要致电mysqli_stmt_get_result

$r = mysqli_stmt_execute($stmt);
if ($r) {
    $result = mysqli_stmt_get_result($stmt);
    if (mysqli_num_rows($result) == 1) {
        ...
    }
}

您也可以简单地测试mysqli_stmt_fetch的结果。它返回一个布尔值,指示是否提取了一行。

$r = mysqli_stmt_execute($stmt);
if (mysqli_stmt_fetch($stmt)) {
    ...
}