Reputation: 1533
I have two tables like this:
table a:
[id, name, roll, address, mark]
table b
[id, name, fee, reg_date]
now I'm running a query like this:
select * from a, b where a.id = b.id;
and I'm using 'mysql_fetch_object' . Now how can I print name of table a and name of table b??
I tried this:
class foo {
public $name;
}
mysql_connect("localhost", "root", "");
mysql_select_db("dodex");
$result = mysql_query("select * from a, b where a.id = b.id");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
to find a way, but I can't.
Upvotes: 0
Views: 784
Reputation: 9335
You can use mysql_fetch_assoc
, instead of mysql_fetch_object
:
$a = mysql_fetch_assoc($result);
echo $a['a.name'];
echo $a['b.name'];
Otherwise, with mysql_fetch_object
, you can do this:
$obj = mysql_fetch_object($result,'foo');
echo $obj->{'a.name'};
echo $obj->{'b.name'};
Upvotes: 2
Reputation: 3295
using select *
is usually a bad idea (this is one reason why).
You should declare each field you're looking for, which then allows you to alias them for clarity:
select a.id as id, a.name as aName, b.name as bName, roll, address, mark, fee, reg_date
from a, b
where a.id = b.id;
also, consider explicit join - it makes things easier to debug at least (in my experience):
select a.id as id, a.name as aName, b.name as bName, roll, address, mark, fee, reg_date
from a
join b on a.id=b.id
Upvotes: 2
Reputation: 1183
Use aliases in your SQL if the tables have columns that share the same name. Otherwise, you can't access the properties by name because they get overwritten.
Upvotes: 0