Jump to content

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.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.