What is fetch_assoc and fetch_row?

I am always confused when fetching data fro the mysql database. As far I understood that fetch_row function will collect all the rows from the database and fetch_assoc do the same but they give the value as associative arrays, now the problem is when I should decide to use fetch_assoc, any example could be appreciate.

I usually use fetch_assoc when it gets too complicated in the code where I use the results of the query to call each part of the result using a numbered index such as $row[0], $row[1], etc. Sometimes it is just easier to keep track of which piece of data I am referring to, if I can use $row[ā€˜first_nameā€™], $row[ā€˜last_nameā€™], and so on. There seems to be less chance of an error then.

1 Like

Yes, the same way I do, so you mean I always have to use assoc function?

No, you donā€™t have to. I know this might not seem very helpful, but use whichever one makes the most sense, or makes it easier for you when you are coding the application.

I always use fetch_assoc as I canā€™t think of a place in my code where itā€™d be easier to refer to the data by number rather than name, especially when I come back to look at it months later.

3 Likes

^that

When Iā€™m working on a script I know that res[0] is the first SELECT column ā€œidā€, res[1] is the second SELECT column ā€œnameā€ etc. I can even do well remembering whatā€™s what when Iā€™m using the variables in other files and not need to look to see what res[3] is.

But not too long after, and especially if I change the SELECT, I would need to hunt things down - not so much fun.

By using descriptive field names such as ā€œidā€, ā€œnameā€ etc. I have a much better chance of knowing what the variables will be, and if the SELECT gets changed it wonā€™t break the script.

About the only time I use numeric keys is to populate drop-down selects.

On a related idea, it is possible to have a query return both numeric and associative keys, and I guess it depends on how the control structure is written. but I canā€™t remember any time having a need for both.

2 Likes

Always turn to the PHP manual when in confusion.
There are clear descriptions for the both functions with vivid examples.

same here. not only it makes the code more understandable to use assoc or object (which is automatically assoc) on a database with well designed column names, but you always access the data in your own order, no matter how the statement reads it. benefit: you get an undefined index error message if the specific key was not returned by your query.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.