为什么 mysqli_stmt::get_result() 方法在作为函数参数传递时会出错?

Why does the mysqli_stmt::get_result() method give an error when passed as a function argument?

提问人:SSteven 提问时间:9/8/2021 最后编辑:SSteven 更新时间:9/8/2021 访问量:32

问:

我编写了一个PHP脚本,用于访问MySQL数据库的Customers表中的行。该脚本包含以下函数:mysqli

      # Print the rows in the result.
      # Note: $rslt should be of type mysqli_result.
      function print_rslt($rslt)
      {
        # Get the number of rows in the result.
        $num_rows = $rslt->num_rows;

        ...
      }

该方法返回一个 type 值(或者在失败时返回布尔值)。mysqli_stmt::get_result()mysqli_resultfalse

因此,我应该能够将以下方法调用直接传递给函数:

# Note: $stmt_SelCusts is a prepared statement of type mysqli_stmt.
print_rslt($stmt_SelCusts->get_result());

但是,当我这样做时,当我尝试在函数中访问时,我收到以下错误:$rslt->num_rows

注意:尝试获取非对象的属性“num_rows”

另一方面,当我执行以下操作时,问题就解决了:

  1. 将方法调用的结果存储在变量中:
     $rslt_SelCusts = $stmt_SelCusts->get_result();

  1. 然后将变量传递给函数:
     print_rslt($rslt_SelCusts);

根据要求,这是主要代码。我省略了一些特定于站点的帮助程序代码 - 此帮助程序代码仅用于连接到 MySQL 数据库。

    <?php

      try
      {
        # ... MySQL DB connection code

        # SQL statement to select rows from the Customers table
        $sql_SelCusts = 
        'SELECT     CustomerID,
                CompanyName,
                Contact,
                email,
                trn_date
                 FROM       Customers
         ORDER BY   CustomerID
             ;';

        # ... MySQL DB connection code

        # Prepare the SQL SELECT statement.
        $stmt_SelCusts = $msi->prepare($sql_SelCusts);

        $stmt_SelCusts->execute();

        $rslt_SelCusts = $stmt_SelCusts->get_result();

        # Print the rows in the result.
        # print_rslt($rslt_SelCusts);           # correct
        print_rslt($stmt_SelCusts->get_result());   # error
      }
      catch (Exception $ex)
      {
        $file = $ex->getFile();
        $line = $ex->getLine();
        $message = $ex->getMessage();
        $code = $ex->getCode();

        error_log("Exception thrown in $file on line $line: 
                  $message [code $code]");

        echo 'Error selecting rows from 
              the Customers table.<br>';
      }
      finally
      {
        $stmt_SelCusts->close();

        $msi->close();
      }

因此,我知道如何解决问题。 但是,首先,造成此错误的原因是什么?

php 函数 mysqli

评论

1赞 u_mulder 9/8/2021
所以,看看它的价值。var_dump($rslt)
1赞 Dharman 9/8/2021
我无法重现这个问题。您能否展示我可以复制和粘贴或使用 phpize.online最小可重复示例
0赞 SSteven 9/8/2021
@Dharman,我已经粘贴了主代码。
1赞 Dharman 9/8/2021
你已经注释掉了,但你似乎也忘了注释它前面的行。 如果您在下面调用它,也需要注释掉,否则您将调用它两次print_rslt($rslt_SelCusts);$rslt_SelCusts = $stmt_SelCusts->get_result()
0赞 SSteven 9/8/2021
@Dharman,你是 100% 正确的。这是根本原因。在我的主程序中(与我粘贴的示例略有不同),实际上我执行了该方法两次。get_result()

答: 暂无答案