简体   繁体   中英

How does PHP/MySQL know to fetch the next row when using mysqli_fetch_array in a while loop?

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM