Page 1 of 1

mysql_fetch_assoc vs mysql_fetch_array

Posted: Mon Mar 21, 2005 5:23 am
by pleigh
what is the major difference between the 2 functions?

if i do this one

Code: Select all

<?php
if (mysql_fetch_array ($result));
?>
some may advise me to use

Code: Select all

<?php
if (mysql_fetch_assoc($result))
?>
instead of using the mysql_num_rows...why is that?i believe that it returns the same result....according to my understanding, correct me if i'm wrong...

another question is, what do you guys prefer to use among the 2 functions?

Posted: Mon Mar 21, 2005 6:11 am
by n00b Saibot
pleigh, please atleast once refer to the manual before shooting a ques. here. you don't know the difference what the hell these two functions do.
you seem to assume that both mysql_num_rows and mysql_fetch_assoc fetch records from db. 8O
the real thing being that
[1] mysql_num_rows returns num. of records returned. not the records itself.
[2] mysql_fetch_assoc returns a record as associative array.

Refer to them here : mysql_num_rows and mysql_fetch_assoc
Hope you can understand the basic difference there. :roll:

Posted: Mon Mar 21, 2005 6:23 am
by AGISB
Well in general both do the same in above context.

Basically you ask if the number of returned rows is <> 0 with the first and you ask if the array is created by any returned rows.

This is only in the instance where you want to know if anything is returned. However this way of coding is bound to be creating errors that you will most likely not find right away. Those kind of errors that let you bump your head at the monitor continously

Posted: Mon Mar 21, 2005 6:45 am
by pleigh
oh yah....im sorry....im too lazy to post the wrong function.....what i mean is mysql_fetch_array and mysql_fetch_assoc.....which of these two are commonly used??why?

Posted: Mon Mar 21, 2005 7:04 am
by Maugrim_The_Reaper
Read the manual???

In general - fetch array will return an array that can be referenced by both a numeral or the key. fetch assoc - only referenced by the key - not number referencing... Why use one over the other? Well, maybe fetch_assoc is slightly faster (it returns only one set of records, not also a second for the numerical referencing).

Posted: Mon Mar 21, 2005 7:19 am
by CoderGoblin
OK I use postgres but the difference is the same...

...fetch_array returns both fieldname and fieldno but if I always use the fieldname why return additional information I never use. I use the fieldname for readability (easy to see what field you are dealing with). Coding to the fieldname also has the advantage that if the table structure changes (columns reordered for some reason or column deleted) you are more likely to get a meaningful error message if trying to use that field.

I have also been known to use extract($row); to get each fieldname as a variable, rather than using $row['fieldname'] all the time.