提问人:SSteven 提问时间:9/8/2021 最后编辑:SSteven 更新时间:9/8/2021 访问量:32
为什么 mysqli_stmt::get_result() 方法在作为函数参数传递时会出错?
Why does the mysqli_stmt::get_result() method give an error when passed as a function argument?
问:
我编写了一个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_result
false
因此,我应该能够将以下方法调用直接传递给函数:
# Note: $stmt_SelCusts is a prepared statement of type mysqli_stmt.
print_rslt($stmt_SelCusts->get_result());
但是,当我这样做时,当我尝试在函数中访问时,我收到以下错误:$rslt->num_rows
注意:尝试获取非对象的属性“num_rows”
另一方面,当我执行以下操作时,问题就解决了:
- 将方法调用的结果存储在变量中:
$rslt_SelCusts = $stmt_SelCusts->get_result();
- 然后将变量传递给函数:
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();
}
因此,我知道如何解决问题。 但是,首先,造成此错误的原因是什么?
答: 暂无答案
评论
var_dump($rslt)
print_rslt($rslt_SelCusts);
$rslt_SelCusts = $stmt_SelCusts->get_result()
get_result()