【问题标题】:Make fetch_assoc match fetch_all exactly使 fetch_assoc 与 fetch_all 完全匹配
【发布时间】:2016-02-16 23:57:50
【问题描述】:

如何将fetch_all 的输出与使用fetch_assoc 的循环完全匹配?我已经围绕fetch_all 构建了代码,但是我的带有 PHP 5.4 的 Bluehost 服务器不足以运行它(我正在和他们谈论它)。这是我一直在使用的,但它不起作用:

public function getAllRecords($query) {
  $results = array();
  $r = $this->conn->query($query) or die($this->conn->error.__LINE__);
  while ($row = $r->fetch_assoc()) {
    $results[] = $row;
  }

  return $results;
}

编辑

此函数有效,但只返回一个结果:

public function getOneRecord($query) {
  $r = $this->conn->query($query.' LIMIT 1') or die($this->conn->error.__LINE__);
  return $result = $r->fetch_assoc();    
}

【问题讨论】:

  • 这里有什么问题?
  • 不返回可用数据。
  • 您是否连接到数据库?您的查询在哪里?
  • 我的其他功能(正在编辑中)有效,只有这个无效。我的确切查询是'select * from nodes',它在开发环境中工作。

标签: php mysql fetch


【解决方案1】:

要让$results 包含与fetch_all 完全相同的输出,您可以使用此循环:

while ($row = $r->fetch_assoc()) {
    $results[] = array_values($row);
}

或者只是在循环中使用fetch_row

while ($row = $r->fetch_row()) {
    $results[] = $row;
}

【讨论】:

  • 在我下面的回答中,您会看到fetch_assoc 不提供与fetch_all 等效的功能,至少我认为在使用mysqlnd 时。
【解决方案2】:

好的,我不知道为什么我的问题被否决了,这是合法的。 fetch_all 就像我之前使用的那样,返回一个行数组作为数组。我所有的函数都是基于将这些数组解析为它们的键值。

fetch_assoc 返回一个关联数组,它在 Javascript 中被解释为一个对象。当然,我的基于数组的解析函数不喜欢这样,这也意味着循环中的fetch_assoc 不等于fetch_all

等效的是fetch_row。正确答案:

public function getAllRecords($query) {
  $results = array();
  $r = $this->conn->query($query) or die($this->conn->error.__LINE__);
  while ($row = $r->fetch_row()) {
    $results[] = $row;
  }

  return $results;
}

【讨论】:

  • 这正是我的回答所说的,-或fetch_assoc中的array_values
  • 哦,我错过了,我的错。
猜你喜欢
  • 1970-01-01
  • 2013-10-05
  • 2020-06-01
  • 2013-02-09
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多