【问题标题】:Why does mysqli num_rows always return 0?为什么mysqli num_rows 总是返回0?
【发布时间】:2011-06-28 07:48:18
【问题描述】:

我一直无法使用 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();
}

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

【问题讨论】:

  • $stmt 上的 var_dump 会产生什么?
  • print_r() 返回:mysqli_stmt 对象([affected_rows] => -1 [insert_id] => 0 [num_rows] => 0 [param_count] => 1 [field_count] => 4 [errno] => 0 [错误] => [sqlstate] => 00000 [id] => 1)
  • 确保数据存在...
  • 我理解它的方式(如果我错了请纠正我,这对我来说是新的)是在调用 $stmt->execute() 之后,执行查询,所以任何在那之后的时间,我应该能够访问检索到的行数?我尝试在 $stmt->execute() 和 $stmt->fetch() 之后回显 $stmt->num_rows。该查询绝对正确,因为它正确填充了表格的单元格(//代码) - 所以有数据。谢谢

标签: php mysqli


【解决方案1】:

您需要在查找 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();
}

请参阅mysqli_stmt::num_rows 上的文档,它就在页面顶部附近(在主描述块中)。

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2021-01-24
    相关资源
    最近更新 更多