php 理解 fetch_assoc()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39267773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:50:22  来源:igfitidea点击:

Understanding fetch_assoc()

phpmethods

提问by Gordog

I am trying to understand how/why fetch_assoc works the way it does. I have the following piece of code:

我试图了解 fetch_assoc 如何/为什么以这种方式工作。我有以下一段代码:

$results = $connectToDb->fetch("SELECT * FROM customer");
$resultsArray = $results->fetch_assoc();
print_r($resultsArray);  //print_r 1

while($row = $results->fetch_assoc()){
    print_r($row);       //print_r 2
}

The query returns 3 rows from a table. Why does the 1st print_r return only the 1st row of the queried data but the 2nd print_r returns all 3? How does putting fetch_assoc into a while loop tell it to do the action more than once? I read that fetch_assoc returns either an associative array or NULL but I'm struggling to understand how the while loop "tells" fetch_assoc to fetch the next row, if that makes sense?

该查询从表中返回 3 行。为什么第一个 print_r 只返回查询数据的第一行,而第二个 print_r 返回全部 3?将 fetch_assoc 放入 while 循环如何告诉它多次执行操作?我读到 fetch_assoc 返回一个关联数组或 NULL 但我很难理解 while 循环如何“告诉” fetch_assoc 获取下一行,如果这有意义吗?

Thank you.

谢谢你。

回答by Andrej Ludinovskov

Lets try to understand your code and how it works:

让我们尝试了解您的代码及其工作原理:

$results = $connectToDb->fetch("SELECT * FROM customer");

A variable $resultshas a collection of rows which are returned by a query. The size of the collection can be from 0 to n.

变量$results具有由查询返回的行的集合。集合的大小可以从 0 到 n。

$resultsArray = $results->fetch_assoc();

This line fetch the first element from the collection. If the collection is empty it will return NULL.

这一行从集合中获取第一个元素。如果集合为空,它将返回NULL

while($row = $results->fetch_assoc()){
}

It can be decoupled in the following steps:

它可以通过以下步骤解耦:

  1. Calculate $row = $results->fetch_assoc()and return array with elementsor NULL.
  2. Substitute $row = $results->fetch_assoc()in whilewith gotten value and get the following statements: while(array(with elements))or while(NULL).
  3. If it's while(array(with elements))it resolves the while condition in Trueand allow to perform an iteration.
  4. If it's while(NULL)it resolves the while condition in Falseand exits the loop.
  1. 计算$row = $results->fetch_assoc()并返回带有元素NULL 的数组
  2. 用得到的值替换$row = $results->fetch_assoc()inwhile并得到以下语句:while(array(with elements))while(NULL)
  3. 如果是,while(array(with elements))它会解决 while 条件True并允许执行迭代。
  4. 如果是,while(NULL)它将解决 while 条件False并退出循环。