gpt4 book ai didi

php - 如何连接同一个类中的两个不同的MySQL DB

转载 作者:行者123 更新时间:2023-11-29 12:31:06 24 4
gpt4 key购买 nike

我有一个名为 dataBase 的类。看起来像这样

    class dataBase
{

private $conexion;
private $paisConexion;
var $db;
function __construct($db='default')
{
$this->db = $db;
include '../settings/variables.php';

if(isset($bbdd)){

$conexion = mysql_connect($bbdd["server"], $pais[0]['user'], $pais[0]['pass']) or die('No se pudo conectar: '.mysql_error());
// Seleccionamos la base de datos
mysql_select_db($x[0]['database']) or die('No se pudo seleccionar la base de datos');

if($conexion)
{
$paisConexion = mysql_connect($bbdd["server"], $pais[$this->db]['user'], $pais[$this->db]['pass']) or die('No se pudo conectar: '.mysql_error());

mysql_select_db($pais[$this->db]['database']) or die('No se pudo seleccionar la base de datos');

}


}
else{
echo 'El sistema no se pudo conectar a la base de datos.';
exit;
}
}

public function execute($sql)
{
$result = mysql_query($sql) or die("ERROR: Ejecuci&oacute;n de consulta: $sql<br>\n");
return $result;
}
}

我正在尝试使用变量 $conexion$paisConexion 与两个不同的数据库建立两个连接。

我的问题是是否可以做这样的事情。

我的意思是假设我正在为这样的类创建一个对象

$obj = 新数据库(1);
$res = obj->execute($sql);

那么类将如何决定它必须使用哪个连接? .

我认为我这样做是错误的。如果有人有任何想法请告诉我

提前致谢

最佳答案

可以做这样的事情,但是你建议的方法对我来说似乎非常有限,所以我冒昧地使用 PDO 编写了一个替代方案,因为 mysql_* 函数已被弃用。 Mysql_* functions official documentation here

通过使用 PHP 提供的 PDO 类,您可以获得参数化查询和事务的好处。 PDO documentation here

为了让您将来更容易添加其他连接,我编写了一个包含绝对简单框架的小类。为了简单起见,我省略了许多事情,例如错误处理,因为这仅用作演示。

/*
* DO NOT USE THIS IN PRODUCTION
*/
class DatabaseConnectionManager {

private $connections = [];

public function __construct(array $credentials) {

foreach($credentials as $identifier => $information) {

$this->connections[$identifier] = $this->openConnection(
$information['host'],
$information['database'],
$information['username'],
$information['password']
);

}

}

public function __destruct() {

/* If the object is destroyed before the script closes or is disrupted (fatal errors), we
* destroy all database connections as good practice.
*/
$this->connections = [];

}

public function getConnection($identifier) {

if(!array_key_exists($identifier, $this->connections)) {
throw new LogicException('Unknown database connection: ' . $identifier);
}

return $this->connections[$identifier];

}

private function openConnection($host, $database, $username, $password) {

$dsn = "mysql:host{$host};dbname={$database}";

return new PDO($dsn, $username, $password);

}

}

通过它,您可以提供一系列不同的数据库连接信息。用法如下。

$credentials = [

'primary' => [
'host' => 'localhost',
'database' => 'number1',
'username' => 'awesome',
'password' => 'secret'
],

];

$connections = new DatabaseConnectionManager($credentials);

要获取可以执行不同数据库相关任务的连接(PDO 对象),只需使用 getConnection() 方法指定连接标识符即可。

$db = $connections->getConnection('primary');

重要

此代码尚未准备好投入生产,仅用于演示目的。几乎没有错误检查或错误处理。如果提供的数组所需参数不足,您将收到错误消息。同时,目前不可能在不对其进行硬编码的情况下向 PDO 对象提供选项。

希望这可以帮助您朝正确的方向发展。

关于php - 如何连接同一个类中的两个不同的MySQL DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27499387/

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