简体   繁体   中英

Loading multiple SQL databases for a query

The background here is that we use a SQL to run a diary and the following commands bring up the results from one specific SQL

if ($_SERVER['HTTP_HOST'] == "localhost") {
    $GLOBALS['dbUsername']     = "admin";
    $GLOBALS['dbPassword']     = "admin";
    $GLOBALS['dbHost']         = "localhost";
    $GLOBALS['dbDatabase']     = "Tracker";
}
else {
    $GLOBALS['dbUsername']     = "admin";
    $GLOBALS['dbPassword']     = "admin";
    $GLOBALS['dbHost']         = "localhost";
    $GLOBALS['dbDatabase']     = "store_3";
}

However we have around 26 of these using "store_1" - "store_26" So to look through them all can take a while. I wanted to simply load multiple at the same time but my SQL + PHP knowledge is not that great

I thought that:

$GLOBALS['dbDatabase']     = "store_3";"store_4"

Would allow me to review more than 1 but this fails. The only other reference to dbDatabase is slightly later in the code

$conn = mysql_connect($GLOBALS['dbHost'], $GLOBALS['dbUsername'], $GLOBALS['dbPassword']);
$data = mysql_select_db($GLOBALS['dbDatabase']);

So I am presuming if I log into multiple databases at the beginning I would also need a way to include them in this statement, any help would be much appreciated.

You can access tables of other database using dbname.tablename

But the databases you want to access should be on same server.

For example:

// Establish connection
$conn = mysql_connect($GLOBALS['dbHost'], $GLOBALS['dbUsername'], $GLOBALS['dbPassword']);

// Select Any one database. Let's say `store_1`
$data = mysql_select_db($GLOBALS['dbDatabase']);

$sql1 = "SELECT * FROM store_1.tablename";
$sql2 = "SELECT * FROM store_2.tablename";
$sql3 = "SELECT * FROM store_4.tablename a JOIN store_5.tablename b ON a.id = b.id";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM