lbennet
lbennet

Reputation: 1103

How to know the table name inside a fetch_array

I am doing a query with union from two different tables and then on the fetch_array loop I would like to know from which table out of the two I am actually grabbing, anyway without adding a flag into the table's structures. ?

Upvotes: 0

Views: 59

Answers (2)

deceze
deceze

Reputation: 522250

The flag doesn't need to be in the table, but can easily be in the query:

SELECT 'table1' as t, ... FROM table1
UNION
SELECT 'table2' as t, ... FROM table2

...

echo $row['t'];

You don't have to select fields from a table, you can simply "select a string literal" too.

Upvotes: 1

beniamin
beniamin

Reputation: 81

If you have columns with identical name in both tables you could use as

SELECT table1.col1 as col1, table1.col2, table1.col3 FROM table1
UNION
SELECT table2.col1 as col4, table1.col5 FROM table2

then when you do $data = fetch_assoc($q) you will have

$data["col1"] // table1.col1
$data["col2"] // table1.col2
-----------------------------
$data["col4"] //table2.col1

Upvotes: 1

Related Questions