为什么mysqli num_rows总是返回0?

oll*_*lie 12 php mysqli

我一直无法使用mysqli获取返回的行数.我每次都回来0,尽管肯定会有一些结果.

if($stmt = $mysqli->prepare("SELECT id, title, visible, parent_id FROM content WHERE parent_id = ? ORDER BY page_order ASC;")){  
    $stmt->bind_param('s', $data->id);  
    $stmt->execute();
    $num_of_rows = $stmt->num_rows;  
    $stmt->bind_result($child_id, $child_title, $child_visible, $child_parent);  

    while($stmt->fetch()){
        //code
    }

    echo($num_of_rows);

    $stmt->close();
}
Run Code Online (Sandbox Code Playgroud)

为什么不显示正确的数字?

irc*_*ell 23

您需要MySqli_Stmt::store_result()在num_rows查找之前调用:

if($stmt = $mysqli->prepare("SELECT id, title, visible, parent_id FROM content WHERE parent_id = ? ORDER BY page_order ASC;")){  
    $stmt->bind_param('s', $data->id);  
    $stmt->execute();
    $stmt->store_result(); <-- This needs to be called here!
    $num_of_rows = $stmt->num_rows;  
    $stmt->bind_result($child_id, $child_title, $child_visible, $child_parent);  

    while($stmt->fetch()){
        //code
    }

    echo($num_of_rows);

    $stmt->close();
}
Run Code Online (Sandbox Code Playgroud)

查看文档MySQLi_Stmt->num_rows,它说它就在页面顶部附近(在主要描述块中)......

  • 我也错过了.它不在PHP.net的大多数示例中. (2认同)