I am trying to understand how/why fetch_assoc works the way it does. I have the following piece of code:
$results = $connectToDb->fetch("SELECT * FROM customer");
$resultsArray = $results->fetch_assoc();
print_r($resultsArray); //print_r 1
while($row = $results->fetch_assoc()){
print_r($row); //print_r 2
}
The query returns 3 rows from a table. Why does the 1st print_r return only the 1st row of the queried data but the 2nd print_r returns all 3? How does putting fetch_assoc into a while loop tell it to do the action more than once? I read that fetch_assoc returns either an associative array or NULL but I'm struggling to understand how the while loop "tells" fetch_assoc to fetch the next row, if that makes sense?
Thank you.
$resultsobject returned from the database is aniterator('cursor'). Aniteratorhas a 'current row'. Every time youfetch_assoc()it returns the current row and automatically advances to to the next row. So, the while loop does not tell the database to return the next row, thefetch_assoc()does that, the while loop ends when it gets an empty row. - Ryan Vincent$resultobject :) It is advance whenever you fetch a row from the result set. see: The Iterator interface. for an example of the PHP iterator. All iterators have the same idea. - Ryan Vincent