了解fetch_assoc() [英] Understanding fetch_assoc()
问题描述
我试图了解fetch_assoc的工作方式/原因. 我有以下代码:
I am trying to understand how/why fetch_assoc works the way it does. I have the following piece of code:
$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
}
查询从表中返回3行. 为什么第一个print_r仅返回查询数据的第一行,而第二个print_r返回所有3行?如何将fetch_assoc放入while循环中,让它多次执行操作?我读到fetch_assoc返回一个关联数组或NULL,但是我在努力理解while循环如何告诉" fetch_assoc获取下一行,如果那有意义吗?
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?
谢谢.
推荐答案
让我们尝试理解您的代码及其工作方式:
Lets try to understand your code and how it works:
$results = $connectToDb->fetch("SELECT * FROM customer");
变量$results
具有查询返回的行的集合.集合的大小可以从0到n.
A variable $results
has a collection of rows which are returned by a query. The size of the collection can be from 0 to n.
$resultsArray = $results->fetch_assoc();
此行从集合中获取第一个元素.如果集合为空,它将返回NULL
.
This line fetch the first element from the collection. If the collection is empty it will return NULL
.
while($row = $results->fetch_assoc()){
}
可以通过以下步骤将其解耦:
It can be decoupled in the following steps:
- 计算
$row = $results->fetch_assoc()
并返回包含元素的数组或 NULL . - 用获得的值替换
while
中的$row = $results->fetch_assoc()
,并获得以下语句:while(array(with elements))
或while(NULL)
. - 如果是
while(array(with elements))
,它将解决True
中的while条件,并允许执行迭代. - 如果它是
while(NULL)
,它将解决False
中的while条件并退出循环.
- Calculate
$row = $results->fetch_assoc()
and return array with elements or NULL. - Substitute
$row = $results->fetch_assoc()
inwhile
with gotten value and get the following statements:while(array(with elements))
orwhile(NULL)
. - If it's
while(array(with elements))
it resolves the while condition inTrue
and allow to perform an iteration. - If it's
while(NULL)
it resolves the while condition inFalse
and exits the loop.
这篇关于了解fetch_assoc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!