Remniscate
Remniscate

Reputation: 31

How fetch_assoc know that you want the next row from the table?

If we would have code like this:

$result = $conn->query('SELECT username FROM users');
$row1 = $result->fetch_assoc();
echo $row1['username'], '<br>';
$row2 = $result->fetch_assoc();
echo $row2['username'], '<br>';

Second echo would show username from second row in table, but why? How fetch_assoc() know that you want the next row in return. Does it have some built-in counter that counts how many times it was called?

Upvotes: 2

Views: 2433

Answers (2)

Ryder Carter
Ryder Carter

Reputation: 1

  1. A while loop runs unless the defined condition doesn't evaluate to false.
  2. The fetch_assoc() function would place its pointer towards the next row once the previous row has been fetched. When it runs out of rows, it returns null, and null always evaluates false, and thus, the while loop stops its execution and the program continues.

Upvotes: 0

MatsLindh
MatsLindh

Reputation: 52802

It keeps a pointer into the list of rows returned. When the query returns data (i.e. when the result object is created), it retrieves all the rows returned by the query.

> row1 foo bar
  row2 baz boo
  row3 tst tmp

When you call fetch_assoc, the row the pointer points to is returned, and the pointer is advanced:

return_val = (row1, foo, bar)
increment pointer

  row1 foo bar
> row2 baz boo
  row3 tst tmp

return return_val    

This is repeated until there is nothing more to return. fetch_assoc then returns null forever.

The last part allows you to use it in a while loop automagically:

while ($row = $result->fetch_assoc()) {
    // do something with $row
}

When fetch_assoc returns null, the while loop terminates and execution continues outside the loop - and the complete result set has been read.

Upvotes: 3

Related Questions