mysql - How do I construct a cross database query in PHP? -
in our last episode (how constructed cross database query in mysql) learned how construct cross database query in mysql. worked great when our hero tried use newfound knowledge in php found best friend fail waiting him.
i took @ mysql_select_db
php. seems imply if want use mysql php, have couple of choices:
use
mysql_select_db
stuck using 1 db @ time. our current setup , putting database namespace identifier doesn't seem work (it works fine in mysql shell know it's not problem our mysql server setup).don't use
mysql_select_db
. of examples i've seen, seems mean have specify db every query make. makes sense since haven't usedmysql_select_db
tell php db want access. makes sad since don't want go through code , prepend db name every query.
is there better this? there way me cross db mysql query in php without having crazy (2)?
clarification: none of proposed answers let me cross db query. instead, allow me access 2 different dbs separately. want solution allows me select foreign_db.login.username, firstname, lastname foreign_db.login, user ...
not make different queries different dbs. it's worth, (2) doesn't work me.
you need databases run on same host.
if so, should able use mysql_select_db on favourite/default db , manually specify foreign database.
$db = mysql_connect($hots, $user, $password); mysql_select_db('my_most_used_db', $db); $q = mysql_query(" select * table_on_default_db a, `another_db`.`table_on_another_db` b a.id = b.fk_id ");
if databases run on different host, won't able join directly. can make 2 queries.
$db1 = mysql_connect($host1, $user1, $password1); $db2 = mysql_connect($host2, $user2, $password2); $q1 = mysql_query(" select id table [..your criteria db1 here..] ", $db1); $tmp = array(); while($val = mysql_fetch_array($q1)) $tmp[] = $val['id']; $q2 = mysql_query(" select * table2 fk_id in (".implode(', ', $tmp).") ", $db2);
Comments
Post a Comment