2 MySQL connections on 2 different hosts

advertisements

I have 2 connection database (MySQL) in different host like this:

//database 1
$dbhost='localhost';
$dbuser='user1';
$dbpass='pass1';
$dbname='dbname1';

//database 2
$dbhostams='192.168.16.3';
$dbuserams='user2';
$dbpassams='pass2';
$dbnameams='dbname2';  

function dbconnection($dbhost,$dbuser,$dbpass,$dbname){
    if(!mysql_connect($dbhost,$dbuser,$dbpass)){
        echo "Error occure on opening connection or database. Period.";
    }else{
        if(!mysql_select_db($dbname)){
            echo "Error occure on select databases !";
        }
    }
}
function dbconnectionams($dbhostams,$dbuserams,$dbpassams,$dbnameams){
    $cxn = mysql_connect($dbhostams,$dbuserams,$dbpassams,$dbnameams);
    if( $cxn === FALSE ) {
        die('mysql connection error: '.mysql_error());
    }else{
        if( !mysql_select_db($dbnameams) ){
            echo "Error occure on select databases !";
        }
    }
}

when i use:

dbconnection($dbhost,$dbuser,$dbpass,$dbname);

at my page code, and use:

dbconnectionams($dbhostams,$dbuserams,$dbpassams,$dbnameams);

at another line of code in same page, error occured, like this:

Warning: Access denied for user: '[email protected]' (Using password: NO) in
/home/firman/html/fdrsimpeg/sdm-aam/include/dbclass.php on line 17

Warning: MySQL Connection Failed: Access denied for user: '[email protected]'
(Using password: NO) in /home/firman/html/fdrsimpeg/sdm-aam/include/dbclass.php
on line 17

mysql connection error:

what must i do to solve this problem?


Your global variables ($dbhost, $dbuser, etc.) are not within the scope of your function calls; for example, if those function calls take place within another function, you will need to declare the variables within the function with the global keyword in order to access them (otherwise PHP thinks you're referring to different variables of the same name that are local to the function):

function foo() {
  global $dbhost, $dbuser, $dbpass, $dbname;
  dbconnection($dbhost,$dbuser,$dbpass,$dbname);
}

Read more on PHP variable scope.