2

Here is the code:

<?php
    $q = 'SELECT * FROM categories ORDER BY category'; 
    $r = mysqli_query($dbc,$q);
    while (list($id,$category) = mysqli_fetch_array($r,MYSQLI_NUM)) {
        echo '<li><a href="category.php?id=' . $id . '" title="' . $category . '">' . $category . '</a></li>';
    }
?>

It looks as though the variable names $id and $category are assigned to a single row fetched from the database through each iteration of the loop. Every time the loop starts over, the next row is chosen. My question is: how does it know to pick the next row in the table?

It's not like the rows are indexed, such that a 'for' loop can step through all the rows of the table. Can someone explain this to me?

3 Answers 3

2

Simply put: because it implements traversable. Just look up the mysqli_result class definition on the PHP site as it will state so. You can actually do this with your own classes as well simply by (correctly) implementing Iterator which will allow objects of that class to be traversable in the very same way mysqli_result is. Also if you look on the page for iterator under examples you'll find a basic mockup of how this is managen inside a class such as mysqli_result.

Sign up to request clarification or add additional context in comments.

Comments

0

That's because $r is an object, which contains information about the latest read row. This is working with streams too. Think of it as it would have an internal counter which gets incremented each time you call _fetch_array(), _fetch_object() or similar.

Comments

0

After each call to mysqli_fetch_array the internal pointer of the resultset that is represented by $r in your example is increased, so the next call return the next element.

Once there are no more elements the returned result is NULL. While control structure takes care to stop the process once NULL is returned.

The resultset is based on output of MySQL query it is not necessary to represent a single table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.