douhu1990 2018-11-02 19:06
浏览 58


I'm learning to interact with a database in PHP. The code below works, but I do not understand how the loop iterates through $result.

  $conn = new mysqli($hn, $un, $pw, $db);
  if ($conn->connect_error) die("DIED: CONNECTION FAILED.");

  $query= "SELECT * FROM table1";
  $result = $conn->query($query);
  if (!$result) die("DIED: QUERY FAILED.");

  while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $who = $row['WHO'];
    $what = $row['WHAT'];

    echo <<<_END
    WHO: $who<br>
    WHAT: $what<br>


I understand that while a $result element is available, it will be assigned to $row and processed in the loop. But how does the interpreter know to move to the next $result element?

The code even works when using a for loop instead, such as...

$row_count = $result->num_rows;
for($j = 0; $j < $row_count; $j++) {
  $row = $result -> fetch_array(MYSQLI_ASSOC);

My question boils down to this: how does the interpreter know to use the next element in $result without needing something like $result[$j]?

  • 写回答

1条回答 默认 最新

  • dongya1875 2018-11-02 19:12

    The query returns a mysqli_result. Per the docs, this object is iterable So every time you call fetch_array(), the result object it is keeping track of which row it is currently on and returning the appropriate result, then moving forward one element in the result set. When there are no more results left, the function returns null which is evaluated as false thus terminating the loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 BDSBAS-B1C和B1C信号有什么不同
  • ¥15 在半圆平面内随机生成点坐标
  • ¥15 系统容量变化的几种多址方式TDMA, CDMA,FDMA,OFDMA 对比,应该给的是一个曲线 图,随着系统容量的增加,几种多址方式性能的对比 图,MATLAB程序仿真折线图
  • ¥15 用visual Studio 写c ++只运行上一个旧代码的运行结果是怎么回事
  • ¥15 系统容量变化的几种多址方式(TDMA,FDMA,OFDMA,CDMA)对比(相关搜索:曲线图)
  • ¥15 worldclim 历史及未来气候数据矫正
  • ¥15 ajax服务器不能下载
  • ¥15 运用c++和opencv实现二维码的识别和三维坐标的建立
  • ¥100 理想汽车的ADB为什么到了国外换了SIM就可以打开?
  • ¥15 k210烧入flash报错error:2005