mysql fetch assoc VS mysql fetch array

后端 未结 10 1856
太阳男子
太阳男子 2020-12-10 04:10

Below are two methods commonly used in most php codes for fetch mysql data .

  1. mysql_fetch_array()
  2. mysql_fetch_assoc()
  3. <
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 05:10

    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

提交回复
热议问题