简体   繁体   中英

Get column with same name from multiple tables using PHP

Ok, so here is what I have right now:

$stuff = mysql_query("SELECT * FROM Table1, Table2") or die(mysql_error());
if ($info = mysql_fetch_array($stuff)) {
    $table1ID = $info['Table1.ID'];
    $table2ID = $info['Table2.ID'];
}

My problem is this does not work. I get nothing. And when I do this:

$stuff = mysql_query("SELECT * FROM Table1, Table2") or die(mysql_error());
if ($info = mysql_fetch_array($stuff)) {
    $table1ID = $info['ID'];
    $table2ID = $info['ID'];
}

It is the same ID (of course). So how do I get the ID of the first table and the second table when they have the same name?

If you want to reference the columns in the resultset by name, then each column in the resultset needs to have a unique name.

So, ditch the " * " and instead give a list of the expressions you want to retrieve, and assign aliases to some of the columns so that each column has a unique name:

SELECT t1.id
     , t2.id AS t2_id
     , t1.somecol            
  FROM Table1 t1
 CROSS
  JOIN Table2 t2

The comma operator is equivalent to a [CROSS] JOIN . Every row in Table1 will be matched with every row from Table2 (a Cartesian product.) And that's a bit odd. (It's not invalid, it's just not the normal pattern. (It's an easy way to make light dimmingly huge resultsets, and I suspect that this is not the actual resultset you want.)

Another option is to reference the columns by position, rather than by name. (But as Marc B will point out "positional field notation" is a bad idea.)

Try aliasing the column names, this will however involve aliasing all the columns you need from the table, which if it is a big table will be a pain

$stuff = mysql_query("SELECT Table1.ID As ID1, Table2.ID As ID2 FROM
Table1, Table2") or die(mysql_error());

// don't need to use mysql_fetch_array, unless you are referencing
// data by col num as well as key name 
if ($info = mysql_fetch_assoc($stuff)) {
    $table1ID = $info['ID1'];
    $table2ID = $info['ID2']; 
}

mysql_fetch_array gives you back a list using both names and numeric values, the names going to be 'ID' for both, so the first one is lost unless you use alias to rename them in your sql. but as you already have a numeric index, just use $info[0] and $info[1]

using alias instead:

$query = "SELECT Table1.ID AS id1, Table2.ID as id2 FROM Table1, Table2";

and then use $info['id1'] and $info['id2']

(Notice: mysql_*-functions is deprecated)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM