【问题标题】:mysqli_stmt::num_rows() returns the wrong valuemysqli_stmt::num_rows() 返回错误值
【发布时间】:2008-09-17 05:27:09
【问题描述】:

我正在使用 mysqli 类和准备好的语句在 PHP 中编写数据库处理程序类。我试图打印出结果。它没有立即工作,所以我决定进行一些调试。我尝试使用 mysqli_statement 类中的 num_rows() 方法,但它一直返回 0。我决定编写一小部分测试代码以使其更简单,这样我就可以看到出了什么问题。然后我能够返回我想要的数据,但是num_rows() 方法仍然返回 0,即使它实际上是在选择和检索一些数据。代码如下:

$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
  die('connection failed');
}

$statement = $mysqli->stmt_init();

$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
    $statement->execute();
    $statement->bind_result($name);
    $statement->fetch();
    $statement->store_result();
    echo $statement->num_rows();
    echo $name; 
}
else
{
    echo 'prepare statement failed';
    exit();
}

预期结果是:

1name

而实际结果是:

0name

谁能告诉我这是为什么?

【问题讨论】:

    标签: php mysql mysqli


    【解决方案1】:

    我想知道 num_rows() 是否相对于当前结果集进行报告。在获取数据之前尝试捕获 num_rows() 。例如

    if($statement->prepare($query))
    {
        $statement->execute();
        $statement->store_result();
        echo $statement->num_rows();
        $statement->bind_result($name);
        $statement->fetch();
        echo $name; 
    }
    

    这有什么影响吗?

    【讨论】:

    • 确实,这就是问题所在。为了让 num_rows() 返回正确的值,store_result() 必须在 fetch() 之前调用。
    • 我是这么想的;获取数据会增加内部行计数器,因此您可以执行类似 while( $statement->num_rows() ) { /* do stuff */ } 之类的操作
    • 我坚信@StevenOxley 的评论是这个问题的答案。
    【解决方案2】:

    num_rows 不是方法,而是属性。

    【讨论】:

      【解决方案3】:

      为了能够使用mysqli_stmt::num_rows(),,您需要将所有行提取到 PHP 中。有两种获取所有内容的方法:使用store_result() 进行缓冲或使用fetch() 手动获取所有行。

      在您的情况下,您已通过调用fetch() 一次开始手动提取。当另一个提取过程正在进行时,您不能调用store_result()。对store_result() 的调用失败并出现错误*。

      $statement->fetch();
      $statement->store_result(); // produces error. See $mysqli->error;
      echo $statement->num_rows();
      

      最简单的解决方案是交换调用这两个方法的顺序。

      $statement->store_result();
      $statement->fetch(); // This will initiate fetching from PHP buffer instead of MySQL buffer
      echo $statement->num_rows(); // This will tell you the total number of rows fetched to PHP
      

      * 由于PHP中的一个bug,这个错误不会在异常报错模式下触发异常。错误信息只能通过mysqli_error() 函数或其对应的属性看到。

      【讨论】:

        【解决方案4】:

        看起来你没有声明 $name。

        另外,请尝试删除 bind_result() 和 fetch(),使其显示如下内容:

        $statement->execute();
        
        $statement->store_result();
        
        printf("Number of rows: %d.\n", $statement->num_rows);
        

        【讨论】:

          猜你喜欢
          • 2015-02-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-27
          • 2011-09-26
          • 1970-01-01
          • 2019-02-03
          相关资源
          最近更新 更多