phpnewbie23
phpnewbie23

Reputation: 13

PHP MYSQL: How to get ambiguous column result from joined table

If I am joining two tables and the result set will have ambiguous coloumn names, how can I retrieve the correct one through php?

Example:

$results = mysql_query("SELECT b.name, m.name FROM Brands as b INNER JOIN Models as m ON b.id = m.brand_id", $connection);

while ($row = mysql_fetch_array($results)) {
  printf("Name: %s", $row["name"]);
}

How can I get access to b.name and m.name from the $row array?

Thank you.

Upvotes: 1

Views: 1321

Answers (2)

Treby
Treby

Reputation: 1320

set an alias to each field using as

    $results = mysql_query("SELECT b.name as bname, m.name as mname FROM Brands as b INNER JOIN Models as m ON b.id = m.brand_id", $connection);

    while ($row = mysql_fetch_array($results)) {
  printf("Name: %s", $row["bname"]);

}

Upvotes: 2

Jason McCreary
Jason McCreary

Reputation: 72971

Alias it in your MySQL query with AS. For example: SELECT name AS display_name, name FROM users;

It's not in PHP, but that's the common way of doing it.

Upvotes: 5

Related Questions