Hello,
I need to select information from two different databases and join them into one web page. I am unsure how to go about doing this. I am not a PHP programmer, any help would be appreciated.
Hello,
I need to select information from two different databases and join them into one web page. I am unsure how to go about doing this. I am not a PHP programmer, any help would be appreciated.
Short practical summary for : if both databases are hosted by the same MySQL server instance, a server-side JOIN using fully qualified identifiers is the simplest and most efficient option (as and were pointing toward). If the databases live on different MySQL servers, a plain single-statement JOIN is not available without extra infrastructure; common alternatives are the FEDERATED storage engine, pulling data into PHP and merging there, or replicating/syncing data into a central database.
Options and tradeoffs:
Example PHP pattern (application-level merge):
try {
$opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$db1 = new PDO('mysql:host=hostA;dbname=dbA;charset=utf8mb4','user','pass',$opts);
$db2 = new PDO('mysql:host=hostB;dbname=dbB;charset=utf8mb4','user','pass',$opts);
$rowsA = $db1->query('SELECT id, colA FROM tableA')->fetchAll(PDO::FETCH_ASSOC);
$rowsB = $db2->query('SELECT id, colB FROM tableB')->fetchAll(PDO::FETCH_ASSOC);
$map = [];
foreach ($rowsA as $r) { $map[$r['id']] = $r; }
foreach ($rowsB as $r) {
if (isset($map[$r['id']])) { $map[$r['id']] = array_merge($map[$r['id']], $r); }
else { $map[$r['id']] = $r; }
}
// $map now holds merged rows keyed by id
} catch (PDOException $e) {
error_log($e->getMessage());
} Practical tips: use indexed join keys, match character sets, limit fetched rows (pagination/batching) for large datasets, use prepared statements to avoid injection (PDO docs), and ensure proper user privileges (MySQL GRANTs).
Jump to Post— NormandP 1You probably need to read this:
http://www.w3schools.com/Sql/sql_join.asp
You probably need to read this:
http://www.w3schools.com/Sql/sql_join.asp
Would that apply with the tables being in two different databases?
Not absolutely sure...
If the 2 databases are located on the same server (same "username", "password" and "localhost")...
I think you should try something like this:
$query="SELECT
first_database_name . first_table_name . optional_column_name ,
second_database_name . second_table_name . optional_column_name
FROM
first_database_name . first_table_name . optional_column_name
INNER JOIN
second_database_name . second_table_name . optional_column_name
etc...
On the same server just do this:
SELECT dbname.tablename.columnname,db2name.table2name.column2name FROM
dbname.tablename, db2name.table2name; (I think you get the idea)
As far as I know you can't select data across multiple servers.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.