How to resolve ambiguous column names when retrieving results?

Dan Burzo picture Dan Burzo · Jan 10, 2009 · Viewed 144.3k times · Source

I have two tables in my database:

NEWS table with columns:

  • id - the news id
  • user - the user id of the author)

USERS table with columns:

  • id - the user id

I want to execute this SQL:

SELECT * FROM news JOIN users ON news.user = user.id 

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

Answer

Christian C. Salvadó picture Christian C. Salvadó · Jan 10, 2009

You can set aliases for the columns that you are selecting:

$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'