无法使用PHP连接到2个不同的远程数据库

时间:2014-09-23 13:37:20

标签: php mysql database mysqli

我有一个这样的代码,其中$_DB_HOST1!= $_DB_HOST2

$dbPnt1 = new Database($_DB_HOST1, $_DB_SCHEMA1, $_DB_USER1, $_DB_PASS1);
$dbPnt2 = new Database($_DB_HOST2, $_DB_SCHEMA2, $_DB_USER2, $_DB_PASS2);

if($dbPnt1->connect())
{
    if($dbPnt2->connect())
    {
        echo "SUCCESS";
    }
    else
        echo "ERROR 2";
}
else
    echo "ERROR 1";

Database类的结构如下:

class Database
{
    // ...

    public function __construct($host, $schema, $username, $password)
    {
        $this->host = $host;        
        $this->schema   = $schema;
        $this->username = $username;
        $this->password = $password;
    }

    public function connect()
    {
        if(!$this->connected)
        {
            $this->link = mysqli_connect($this->host,$this->username,$this->password);

            if($this->link)
            {
                $this->db = mysqli_select_db($this->link, $this->schema);

                if($this->db)
                {
                    $this->connected = true;
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }
        else
            return true;
    }

    // ...
}

问题是我似乎无法连接到同一个PHP脚本中的两个不同的数据库主机。我的代码中是否有一个我没有看到的错误?

由于

1 个答案:

答案 0 :(得分:0)

嗯,我认为你应该在你的连接功能中返回$this->link。否则,您的变量中会有truefalse

如果检查数据库类中的连接并且在连接不起作用时抛出错误,则可能会更容易。

class Database {
    private $link;

    private $connected;

    public function __construct($host, $schema, $username, $password) {
        $this->host = $host;        
        $this->schema   = $schema;
        $this->username = $username;
        $this->password = $password;

        return $this->connect();
    }

    public function connect() {
        if(!$this->connected) {
            $this->link = mysqli_connect($this->host,$this->username,$this->password);

            if($this->link) {
                $this->db = mysqli_select_db($this->link, $this->schema);

                if($this->db) {
                    $this->connected = true;
                    return $this->link;
                }
                else
                    throw new Exception('Database not available');
            }
            else
                throw new Exception('Connection not available');
        }
        else
            return $this->link;
    }

    // ...
}

$dbLink1 = new Database($_DB_HOST1, $_DB_SCHEMA1, $_DB_USER1, $_DB_PASS1);
$dbLink2 = new Database($_DB_HOST2, $_DB_SCHEMA2, $_DB_USER2, $_DB_PASS2);

如果你有一些mysqli函数,第一个参数是链接。然后你有完整的链接,你可以使用它。我还没有测试过。但这对你来说只是一个短暂的暗示。

mysqli_query ( $dbLink1 , string $querg );