Search code examples
phpmysqlconnectionmysql-select-db

PHP - Two MySQL connections, only second one works


I've looked every where, probably googled every variation of my question I could come up with and I've tried all of the suggestions... I'm trying to connect to two different DBs in two different locations ($local and $remote) and only the second one works. Here is a sample of my code ("..." = hidden):

//-------------Local DB Connection:
    $local = mysql_connect("localhost","root","...");
    if (!$local)
    {
        die('Could not connect: ' . mysql_error());
    }
    $sel1 = mysql_select_db("new", $local);
//-------------Remote DB Connection:
    $remote = mysql_connect("...","...","...",true);
    if (!$remote)
    {
        die('Could not connect: ' . mysql_error());
    }
    $table = "...";

//---------function selecting from local:
    function fncGrabNemsis($ele,$val){
        mysql_select_db("new", $local);
        $result = mysql_query("SELECT * FROM new.tblvalues
        WHERE fldelement='$ele' AND fldcode='$val'",$local);
        $tmprow = mysql_fetch_array($result);
        return (isset($tmprow['fldvariable'])?$tmprow['fldvariable']:$val);
    }

//----------Select run from Remote:
        mysql_select_db("ImdxTest", $remote);
        $result = mysql_query("SELECT * FROM ImdxTest.$table WHERE ClientID = ... AND IncidentNum = '$fldINCID'", $remote) or die(mysql_error());
        $row = mysql_fetch_array($result);

I've tried moving the mysql_select_db() function calls everywhere you can think of and just about everything else... What happens is, I get php errors saying that $local is not defined or that the mysql function that are trying to use the $local connection are expecting parameters to be resources!? I know for a fact that both connections work because individually they both work. Only the second connection ($remote) works... Thanks a lot for any suggestions!


Solution

  • fncGrabNemsis needs the global variable $local:

        function fncGrabNemsis($ele,$val){
            global $local;
            mysql_select_db("new", $local);
            $result = mysql_query("SELECT * FROM new.tblvalues
            WHERE fldelement='$ele' AND fldcode='$val'",$local);
            $tmprow = mysql_fetch_array($result);
            return (isset($tmprow['fldvariable'])?$tmprow['fldvariable']:$val);
        }
    

    This should help you understand better: http://php.net/manual/en/language.variables.scope.php