简体   繁体   中英

Multiple mysql database usage and management in php

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?

That seems to be ok. An alternative would be to use the class mysqli instead of the functions in order to manipulate objects instead of identifiers.

Quite good, although you shoul try not to duplicate your code :

function db_connect($which) {
    if($which == "main") {
        $host = HOSTNAME_1;
        $db = MAIN_DB;
    } elseif($which == "stats") {
        $host = HOSTNAME_2;
        $db = STATS_DB;
    } else {
        throw new Exception('unknown db');
    }
    return mysqli_connect($host, USER, PASSWORD, $db);
}


$maindb = db_connect("main");
$statsdb = db_connect("stats");

You could store your databaseconfigs in arrays and use that. That's how codeigniter does it.

function get_database_config(){
    $config['main']['hostname'] = "host1";
    $config['main']['user']     = "user1";
    $config['main']['password'] = "pass1";
    $config['main']['database'] = "database1";

    $config['stats']['hostname'] = "host2";
    $config['stats']['user']     = "user2";
    $config['stats']['password'] = "pass2";
    $config['stats']['database'] = "database2";

    return $config;
}

function db_connect($db)
{
    $config = get_database_config();
    return mysqli_connect( 
            $config[$db]['hostname'],
            $config[$db]['user'],
            $config[$db]['password'],
            $config[$db]['database']
    );
}

If you don't want to work with an associative array and prefer to work with constants, you could name your constants as MAIN_HOSTNAME, STATS_HOSTNAME, ... and use constant($which . '_HOSTNAME') as input for mysqli_connect().

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