Web Hosting Talk







View Full Version : Difference between mysql_fetch


Kayuchi
01-04-2006, 10:04 AM
Hi guys,

What is the difference between mysql_fetch_assoc, mysql_fetch_object and mysql_fetch_array?

There isnt much difference, is there?

Why would you use an other way of fetching if you know for instance only mysql_fetch_assoc?

thanks,

kalok

Burhan
01-04-2006, 10:10 AM
mysql_fetch_array fetches both associative arrays and numerically indexed arrays by default. This means that if you use mysql_fetch_array, you can access your results both by positional index (numerically) and by the name of the column (associatively). In order words, $row[0] and $row['fname'] will both work. You can change its behavior by the optional second argument, a constant that will make the function return only numeric, or only associative arrays.

mysql_fetch_assoc fetches the results as an associative array only. It is the same as using mysql_fetch_array with MYSQL_ASSOC flag.

The above two functions return arrays, mysql_fetch_obj returns the result set as an object.

On the surface the differences may seem negligible, but there are some operations (such as iteration) that only work on arrays and not objects, and vice versa. So it comes downs to how and where you want to use your result set data.

innova
01-04-2006, 10:14 AM
It really depends if you prefer to work with an associative array or an object.. Personally I use fetch_assoc as a matter of convention.

I would recommend against using fetch_array. By default, it will fetch data as both associative AND numeric-indexed arrays unless you specify the optional parameter. In other words,

mysql_fetch_array($result, MYSQL_ASSOC) == mysql_fetch_assoc($result)

From the php.net manual, speaking of mysql_fetch_object:

Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).

$_patch
01-04-2006, 10:55 AM
I like to use mysql_fetch_assoc for retrieving table fields. it lets me do something like $row['IDuser'];

Kayuchi
01-04-2006, 12:28 PM
aaah thanks guys, made a lot clear for me

dabluedude
01-04-2006, 02:22 PM
I always use mysql_fetch_assoc for fetching because the results you get are easier to understand, especially with queries where you fetch a lot of different columns, because you would have to track every column down (where does it stand for: $row[234]??) while debugging or just creating your app.