了解fetch_assoc() [英] Understanding fetch_assoc()

查看:120
本文介绍了了解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:

  1. 计算$row = $results->fetch_assoc()并返回包含元素的数组 NULL .
  2. 用获得的值替换while中的$row = $results->fetch_assoc(),并获得以下语句:while(array(with elements))while(NULL).
  3. 如果是while(array(with elements)),它将解决True中的while条件,并允许执行迭代.
  4. 如果它是while(NULL),它将解决False中的while条件并退出循环.
  1. Calculate $row = $results->fetch_assoc() and return array with elements or NULL.
  2. Substitute $row = $results->fetch_assoc() in while with 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 True and allow to perform an iteration.
  4. If it's while(NULL) it resolves the while condition in False and exits the loop.

这篇关于了解fetch_assoc()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆