Search code examples
phpmysqldatabasedisconnect

php - disconnecting and connecting to multiple databases


I want to be able to switch from the current db to multiple dbs though a loop:

$query = mysql_query("SELECT * FROM `linkedin` ORDER BY id", $CON ) or die( mysql_error() );
if( mysql_num_rows( $query ) != 0 ) {
    $last_update = time() / 60;
    while( $rows = mysql_fetch_array( $query ) ) {
        $contacts_db = "NNJN_" . $rows['email'];
        // switch to the contacts db
        mysql_select_db( $contacts_db, $CON );
        $query = mysql_query("SELECT * FROM `linkedin` WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );
        if( mysql_num_rows( $query ) != 0 ) {
            mysql_query("UPDATE `linkedin` SET last_update = '{$last_update}' WHERE token = '" . TOKEN . "'", $CON ) or die( mysql_error() );   
        }else{
            mysql_query("INSERT INTO `linkedin` (email, token, username, online, away, last_update) VALUES ('" . EMAIL . "', '" . TOKEN . "', '" . USERNAME . "', 'true', 'false', '$last_update')", $CON ) or die( mysql_error() );
        }
    }
    mysql_free_result( $query );
}
// switch back to your own
mysql_select_db( USER_DB, $CON );

It does insert and update details from the other databases but it also inserts and edits data from the current users database which I dont want. Any ideas?


Solution

  • Never use the php mysql_select_db() fundtion - as you've discovered the code (and the coder) gets very confused very quickly.

    Explicitly state the DB in the queries:

    SELECT * FROM main_database.a_table....
    
    UPDATE alternate_db.a_table SET...
    
    REPLACE INTO third_db.a_table...
    

    C.