【问题标题】:Call to undefined method mysqli_result::fetch()调用未定义的方法 mysqli_result::fetch()
【发布时间】:2020-01-19 15:27:09
【问题描述】:

我可以使用fetch_assoc()fetch_all()、...和fetch_row() 中的任何一个从get_result() 获取数据,但是当我尝试仅使用简单的fetch() 时,我得到了这个错误

未捕获的错误:调用未定义的方法 mysqli_result::fetch()

这是因为使用了get_result()吗?还是我在以下代码中遗漏了其他内容

$stmt = $conn->prepare($SQL);
$stmt->bind_param("s", $date);
$stmt->execute();
$result = $stmt->get_result();
//$row = $result->fetch_assoc();
//$row = $result->fetch_all();
//$row = $result->fetch_row();
$row = $result->fetch();

【问题讨论】:

  • fetch() 对象上没有 fetch() 方法。您可能正在查看mysqli_stmt 对象的fetch() 方法。
  • @AlexHowansky 我相信您可以将其作为答案。不管多么费力,这是一个公平的问题,据我所知,不是重复的。

标签: php mysqli


【解决方案1】:

变量$stmtmysqli_stmt 类的对象。这个类有一个名为fetch() 的方法,它返回一个布尔值(真/假)。它仅与bind_result() 结合使用

$stmt = $conn->prepare('SELECT myCol, myOtherCol FROM myTable WHERE dt=?');
$stmt->bind_param("s", $date);
$stmt->execute();
// The columns in SQL will be bound to the PHP variables
$stmt->bind_result($variable1, $variable2);
while ($stmt->fetch()) {
    // This will fetch each record from the prepared statement one by one
    printf ("myCol is %s and myOtherCol is %s\n", $variable1, $variable1);
}

$stmt->get_result() 返回一个 mysqli_result 类的对象(顺便说一句,它可以使用 foreach 遍历)。这个类有不同的方法,但是没有fetch()方法。

  • fetch_all() 返回一个数组数组。顾名思义,它一次返回结果集中的所有记录。
    $result = $stmt->get_result();
    $allRecords = $result->fetch_all(\MYSQLI_ASSOC);
    echo json_encode($allRecords);
    
  • fetch_array() 将每条记录一一返回为一维数组
    $row = $result->fetch_array();
    printf("%s (%s)\n", $row["myCol"], $row["myOtherCol"]);
    
  • fetch_assoc() 等价于 fetch_array(\MYSQLI_ASSOC)
  • fetch_row() 等价于 fetch_array(\MYSQLI_NUM)
  • fetch_object() 将每条记录作为对象一一返回。
    $row = $result->fetch_object();
    printf("%s (%s)\n", $row->myCol, $row->myOtherCol);
    

但是,为了简单起见,您可以直接在 mysqli_result 上循环,这会将每一行作为一个关联数组。

foreach($stmt->get_result() as $row) {
    printf("%s (%s)\n", $row["myCol"], $row["myOtherCol"]);
}

【讨论】:

    【解决方案2】:

    mysqli_result 对象上没有 fetch() 方法。目前尚不清楚您期望fetch() 返回什么,但您可能正在查看mysqli_stmt 对象的fetch() 方法。

    【讨论】:

    • 谢谢 Alex,但我们不是在 bind_result 中使用 mysqli_result 吗?那么为什么要在那里工作呢?
    • 不,bind_result()fetch() 都是 mysqli_stmt 对象上的方法。您可以使用$stmt->get_result(),然后使用$result->fetch_whatever() $stmt->bind_result(),然后使用$stmt->fetch()。完成同一件事的两种不同方法。
    • fetch() 不在 mysqli_stmt 根据 php 手册:php.net/manual/en/class.mysqli-stmt.php 所以它不能与 get_result 一起使用。只有 bind_result 因为它来自 mysqli-stmt.prepare
    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    相关资源
    最近更新 更多