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
.
<?php
require_once('./login.php');
$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>
_END;
}
$result->close();
$conn->close();
?>
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]
?