Below are two methods commonly used in most php codes for fetch mysql data .
mysql_fetch_array()
mysql_fetch_assoc()
An additional point to keep in mind is that fetch_assoc()
may not return every column you expect. If 2 output columns would have the same name, only the last instance of that column will be retrieved by fetch_assoc()
. For example, the following query:
SELECT * FROM orders LEFT JOIN line_items ON orders.id = line_items.order_id
Assuming both tables have a column called id
, the resulting associative array would have a key called id
whose value is set to line_items.id
and you would not be able to retrieve orders.id
from the result!
You can circumvent this duplicate column names issue and continue to use fetch_assoc()
by manually aliasing your SELECT
columns, giving each column a unique alias:
SELECT
o.id AS order_id, #unique alias
i.id AS line_item_id, #unique alias
o.date,
i.qty,
i.price
FROM orders o
LEFT JOIN line_items i ON i.order_id = o.id
Or you can switch to using fetch_array()
, which will allow you to access either id
by index instead of by key
mysql_fetch_assoc()
would probably be the better choice. There is a slight performance hit (the mysql extension needs to look up the column names, but that should only happen once, no matter how many rows you have), but probably not enough to justify using mysql_fetch_array()
instead. mysql_fetch_array()
can be useful if you're only selecting one column though.
It depends on how your tables are setup:
mysql_fetch_array()
essentially returns two arrays one with numeric index, one with associative string index.
So using mysql_fetch_array()
without specifying MYSQL_ASSOC
or MYSQL_NUM
, or by specifying MYSQL_BOTH
will return two arrays (basically what mysql_fetch_assoc()
and mysql_fetch_row()
would return) so mysql_fetch_assoc()
is faster.
If you have your table setup right and query written properly mysql_fetch_assoc()
is the way to go, code readability wise $result['username']
is easier to understand than $result[0]
.
The benchark shown in your example uses mysql_fetch_array() without any argument to specify MYSQL_ASSOC or MYSQL_NUM, so it defaults to MYSQL_BOTH... this will rather skew the result as it has to load twice as many array elements as mysql_fetch_assoc(). So I'd suggest it isn't a valid benchmark.
In reality, there should be very little to differentiate between mysql_fetch_array() with MYSQL_ASSOC and mysql_fetch_assoc(), and it cerayinly won't be the biggest overhead in your script.