Page 1 of 1

mysql_fetch_*

Posted: Thu Jul 14, 2005 12:40 pm
by Ree
take a look at the following:

Code: Select all

$query = 'select head, body from news';
$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result))
{
  echo $row['head'] . '<br>';
  echo $row['body'] . '<br><br>';
}
now what i would like to ask is how does PHP know that it needs to jump to the NEXT row after the {stuff} part of the while loop is executed? there isn't any indication, but it does select the next row. for example, mysql_result function is clear - you indicate the row you want to use elements of by using an int. don't get me wrong, i understand how the above while works, but for me it would appear that the given loop is infinite: from this ($row = mysql_fetch_assoc($result)) you get the first row of the $result and if the latter assignment expression is true (provided the table has records, it is), the {stuff} is executed. then we start over with the same again and again - assign the first row, check, do {stuff} - seems like infinite. where's the indication 'select the next row'? there isn't any and it doesn't need it, but it does select the next row. yeah, it's convenient to have it that way, but for me it seems like it's doing more than it is told to do. :)

Posted: Thu Jul 14, 2005 12:48 pm
by onion2k
Every time you call a mysql_fetch function it increments a counter associated with that particular resultset. The next time it's called it gets the result that the counter says it should get, and increments the counter again. Eventually the counter is greater than the number of results, so it exits the while loop.

"fetch", in my mind, means it should go away and get the record and tell the database it's got the record. So it's not really doing more than it says it does.

You can reset, or change, the internal counter using mysql_data_seek();

Alternatively, if you don't like the way fetching works, just use mysql_result(). You should bear in mind that it's really bloody slow though.

Posted: Thu Jul 14, 2005 12:58 pm
by Ree
onion2k wrote:Every time you call a mysql_fetch function it increments a counter associated with that particular resultset. The next time it's called it gets the result that the counter says it should get, and increments the counter again. Eventually the counter is greater than the number of results, so it exits the while loop.
that's exactly what i had in mind - counter. there's no visible counter var in the code, that's why it seemed to me like it's doing the required on its own (as compared to mysql_result, which indeed is slow as you had mentioned). if i understood it correctly, according to your explanation, it has a kind of 'internal' counter. now having this in mind, it now makes sense to me. :)