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