Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.