K
K
king_men2016-02-06 17:29:50
PHP
king_men, 2016-02-06 17:29:50

How to make a mysql query to select from 2 databases?

Good day. I need to fetch data from two databases.
Please tell me what I'm doing wrong:

$dbh1 = mysql_connect('host', 'log', 'pass'); 
$dbh2 = mysql_connect('host', 'log', 'pass'); 

mysql_select_db('db_name', $dbh1);
mysql_select_db('db_name2', $dbh2);

$query = "SELECT `db_name1`.`content`.`title`, `db_name2`.`news`.`title` 
FROM `db_name1`.`content` LEFT JOIN `db_name2`.`news`
ON `db_name1`.`content`.`title` = `db_name2`.`news`.`title` ";
$query = mysql_query($query);
var_dump($query);

Null is output.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Kubintsev, 2016-02-06
@king_men

If the databases are on different servers, then such a trick with the 1st request will not work

S
Sergey Vushnyakov, 2016-02-06
@leto2015

SELECT <write here the fields from the two bases that we want to display after the query>
FROM <write the first base (table)
here> INNER JOIN <write the second base (table) here>
ON <write the condition here, if the fields match, the fields should be displayed >
--------------------------------
Read Kevin Yank, p. 123 (on p. 126, everything is detailed) .
Good luck.

M
Mikhail, 2016-02-06
@mix_gorbachev

SELECT t1.*, t2.*
FROM database1.table1 AS t1
INNER JOIN database2.table2 AS t2 ON t2.field1 = t1.field1
You connect to the DBMS and then select the active database (which is not necessary in this case).
Read documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question