Page 1 of 1

Problem when use "LEFT JOIN"

Posted: Thu Nov 27, 2003 8:46 am
by detrox
In my project, I have to run

Code: Select all

$res = mysql_query("SELECT * FROM poll_opt LEFT JOIN poll_sub ON poll_opt.subid = poll_sub.id");

while ($data = mysql_fetch_array($res)) {
...
   poll_id = $dataї"id"];
...
}
but I have a field named "id" in both poll_opt and poll_sub, how can I distinguish them when i use $data["id"].

Posted: Thu Nov 27, 2003 9:34 am
by xisle
specify your fields in the SELECT and use an alias for the id
'table1.id as first_id, table2.id as second_id'

retrieve with poll_id = $data["first_id"];

Posted: Thu Nov 27, 2003 1:38 pm
by detrox
Thanks very much. It makes great help.

Posted: Sat Nov 29, 2003 5:16 pm
by JAM
Just adding;
As you use mysql_fetch_array($res) you also get the numerical instance of the keys in the array fetched...

Code: Select all

$dataї'id'] = 'foo'
$dataї0] = 'foo'
$dataї'id'] = 'bar' // heres your problem, what id to use...
$dataї1] = 'bar' // workaround usage
so, even if both are 'named' id, you can distinguish them using;

Code: Select all

poll_id = $dataї0]
other_poll = $dataї9] // or whatever...