Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql php selecting fields from 2 tables, with the same field names [duplicate]

Tags:

php

mysql

prefix

So I have a bespoke CMS that allows dynamic creation of forms and lists etc. I have noticed an issue where it grabs the data for the list, which is conflicting with an approval table in the database.

The problem is, if the table with the data has fields names the same as field names in the approvals table, then when i mysql_fetch_array and it returns the values in an array, it will only return one field name

So an example of what is being returned

Array
(
    [id] => 1
)

And ideally I would want it returned as

Array
(
    [approvals.id] => 1
    [affiliates.id] => 2
)

So how can I make it prefix the table name to the results array to counteract field names called the same thing? I dont want to go through changing the field names as its pretty embedded.

like image 761
Horse Avatar asked Nov 21 '12 10:11

Horse


3 Answers

Normally you use an alias in the SQL sentence:

SELECT table1.id as t1_id, table2.id as t2_id FROM .....

Then when you have the fetching, you will access it this way:

echo $row['t1_id'];
like image 138
aleation Avatar answered Oct 18 '22 14:10

aleation


Use mysql alias

approvals table id alias as [id AS approvals.id]

affiliates table id alias as [id AS affiliates.id]

like image 34
som Avatar answered Oct 18 '22 14:10

som


Use an alias in the query:

SELECT approvals.id AS approvals_id, affiliates.id AS affiliates_id ...

The associative array will then contain:

echo $row['approvals_id'];
like image 24
MrCode Avatar answered Oct 18 '22 12:10

MrCode