My script requires connections to several databases. Some parts only need to connect to one, which is all fine and dandy, however in some cases I need to perform queries on different database in a single script execution.
Currently I’m doing something like this:
function db_connect($which) {
if($which == "main") {
$maindb = mysqli_connect(HOSTNAME_1, USER, PASSWORD, MAIN_DB);
return $maindb;
} elseif($which == "stats") {
$statsdb = mysqli_connect(HOSTNAME_2, USER, PASSWORD, STATS_DB);
return $statsdb;
}
}
$maindb = db_connect("main");
$statsdb = db_connect("stats");
I maintain the actual hostname, username, password and db name in a config file full of constants.
I then use the respective links on different queries.
Is there a cleaner way to do this?
Quite good, although you shoul try not to duplicate your code :