Jump to content

Just how does mysql_fetch_row() work??


elgati

Recommended Posts

I have a nagging question about loops when using mysql_fetch_row().

 

In other OOP languages whenever you use a for loop you have to use the variable you are incrementing to point to the right element in the array, but when you use mysql_fetch_row() you don't need to.

 

Why is that?

 

For example:

in js/php/as you write:

for(i=0; i<length; ++i) { doSomething [i]row; }

 

but when calling mysql_fetch_row you just write:

for(i=0; i<length; ++i) { doSomething row; }

 

I'm just curious about how the loop finds its way to next row. Is it built in the mysql_fetch_row function already?

 

Link to comment
https://forums.phpfreaks.com/topic/255457-just-how-does-mysql_fetch_row-work/
Share on other sites

Typically, you'd use a while() loop and mysql_fetch_row() will keep advancing the data pointer until it iterates over all the results in the results set and finally returns FALSE. If that isn't what you were referring to, you'll need to clarify the question.

 

while( $array = mysql_fetch_row($result) ) {
     echo "$array[0] $array[1] $array[2]"; // Etc.
}

Thanks for the prompt reply.

 

It's more of a general question.

 

I'm reading through this book: http://lpmj.net/ so upon further reading I found my answer.

 

I was asking why do this: http://lpmj.net/examples.php?c=10&e=6&x=php

 

Instead of this: http://lpmj.net/examples.php?c=10&e=5&x=php

 

but I think I understand now.

 

Thanks!

If you wanted a row counter as well as the data, you could use a for loop in this fashion:

for ($i=0; $row=mysql_fetch_row($res); $i++){
    //$row has the data
    //$i is the row number
}

 

Using your for loop variable (ie, $i) is not required in any language.  In most cases though you need it because that is how you access the data. 

 

As mentioned, when you want to loop over something but don't need a counter (which is typically the case with db results) you're better off just using a while() loop and avoid the variable all together.

 

As for your two examples, a single call to mysql_fetch_array/assoc is better than several calls to mysql_result.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.