为什么mysqli num_rows总是返回0?

时间:2011-02-16 12:11:49

标签: 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();
}

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

2 个答案:

答案 0 :(得分:23)

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

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();
}

请参阅the docs on MySQLi_Stmt->num_rows,它说它就在页面顶部附近(在主要说明栏中)...

答案 1 :(得分:-2)

尝试在if(声明)之后设置$num_of_rows - 在bind_param之前......除非这会改变你的结果。没有更多信息很难分辨。

相关问题