gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:44:47 25 4
gpt4 key购买 nike

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

谢谢

最佳答案

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

关于php - 无法使用 PHP 连接到 2 个不同的远程数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25996584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com