tags:

views:

64

answers:

2

I am using the following SQL query:

Select * from table1 as t1, table2 as t2 where t1.id = t2.col

but my problem is that both the tables have fields with same name, place. So how can I select the column with name place from table2 in my PHP code? I want to use the following php code

 while($row_records = mysql_fetch_array($result_records))
    {

            <?  echo $row_records['place']; ?>

     }

How can I fetch the field from particular table?

+3  A: 

Why don't you use the table alias and the field name. For example,

    Select t1.place as t1_place, t2.place as t2_place 
      from table1 as t1, table2 as t2 where t1.id = t2.col

In your PHP code you can select it using

while($row_records = mysql_fetch_array($result_records))
    {
    echo $row_records['t1_place']; 
    echo '<br />';
    echo $row_records['t2_place']; 
    }
Wbdvlpr
+6  A: 

Never use...

Select * from ...

... in a production environment - Always specify explicitly which columns you want to return.

Thus you could amend your SQL to:

Select t1.Place as T1Place, t2.Place as T2Place
  from table1 as t1, table2 as t2 where t1.id = t2.col

So in your PHP you would have:

 while($row_records = mysql_fetch_array($result_records))
 {

        <?  echo $row_records['T2Place']; ?>

 }
CJM
+1 for 'SELECT *' comment
Jonathan Leffler
"never" is a bit strong.
hop
It perhaps matters less with dynamic languages; it mattered intensely with languages like COBOL, but the advice is still sound. Suppose the table is altered to add 3 extra fields: a picture, a movie clip, and a PDF file. Your query does not use any of them but your code now pays the cost of transferring 3 monstrous (multi-megabyte) field values only to ignore them. It's funny: the users are now complaining about the performance of your application. If you had not written the lazy 'SELECT *', you would not have suffered the indignity of having to go back and fix up your bodged up lazy code.
Jonathan Leffler
@Hop - Jonathan has explained one good reason; another is clarity. However, I'm genuinely open to alternative scenarios...
CJM
thanks for all the answeres and comments i just accpeted it and also upvoted.