【问题标题】:Cannot connect to 2 different remote databases using PHP无法使用 PHP 连接到 2 个不同的远程数据库
【发布时间】:2014-09-23 13:37:19
【问题描述】:

我有这样的代码,其中$_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 脚本中连接到 2 个不同的数据库主机。我的代码中是否有我没有看到的错误?

谢谢

【问题讨论】:

  • 它的反应是什么?用户名/密码/主机/数据库名称是否正确?
  • 它看起来应该对我有用。

标签: php mysql database mysqli


【解决方案1】:

嗯,我认为您应该在连接函数中返回 $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 );

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 2014-08-26
    • 1970-01-01
    • 2019-10-16
    • 2019-11-01
    • 2018-10-15
    相关资源
    最近更新 更多