gpt4 book ai didi

php - PDO 连接到多个数据库

转载 作者:搜寻专家 更新时间:2023-10-30 23:12:01 24 4
gpt4 key购买 nike

我有下面的 PDO 类:

class DB {

private $dbh;
private $stmt;

static $db_type;
static $connections;

public function __construct($db, $id="") {

switch($db) {
case "db1":
try{

$this->dbh = new PDO("mysql:host=localhost;dbname=ms".$id, 'root', '', array( PDO::ATTR_PERSISTENT => true ));
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
break;
case "db2":
try{
$this->dbh = new PDO("mysql:host=localhost;dbname=users", 'root', '', array( PDO::ATTR_PERSISTENT => true ));
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
break;
}
self::$db_type = $db;
}

static function init($db_type = ""){

print_r(self::$connections);


if(!isset(self::$connections[$db_type])){
self::$connections[$db_type] = new self($db_type);
}

return self::$connections[$db_type];
}

public static function query($query) {

self::$connections[self::$db_type]->stmt = self::$connections[self::$db_type]->dbh->prepare($query);
return self::$connections[self::$db_type];
}

public function bind($pos, $value, $type = null) {

if( is_null($type) ) {
switch( true ) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}

self::$connections[self::$db_type]->stmt->bindValue($pos, $value, $type);
return self::$connections[self::$db_type];
}

public function execute() {
return self::$connections[self::$db_type]->stmt->execute();
}
}

接下来我尝试:

$id = 1;
DB::init('db1', $id);

这会返回一个错误:

Error!: SQLSTATE[HY000] [1049] Unknown database 'ms'<br />

为什么我的数据库名称在连接期间是 ms 而它应该是 ms1?谢谢。

最佳答案

您的初始化方法的签名是:

 static function init($db_type = "")

这意味着它只接受一个参数,而你是这样调用它的:

DB::init('db1', $id);

这行不通。另外:你需要阅读static,持久连接和注入(inject)与单例......你的代码充满了问题。首先:始终指定访问修饰符。
你的标题表明想要使用多个连接,但你一遍又一遍地重新分配 $db_type 属性(它是静态的,因此在所有实例中共享)。
您正在尝试使用 Singleton 模式,无论如何这在 PHP 中毫无意义,但在您的情况下更是如此,因为您的构造函数是公共(public)的,仍然......

仅在必要时才使用静态,即便如此:仔细思考:大多数时候,不得不使用静态意味着不得不承认设计错误。

query 方法只接受 1 个参数:一个字符串,并在最后建立的连接上执行该查询。您无法选择将在哪个数据库上运行此查询。如果不危险,那就比这更危险了,我不想成为它的 SCSS ,但我不能用任何其他方式来表达它:这是糟糕的代码 .

请重构这段代码,如果我发现自己不得不使用这个类,我会创建自己的 PDO 实例并使用它。不管你怎么看:你极大地限制了一个人可以执行的查询,但你不能拒绝我对 PDO 本身的访问......

关于php - PDO 连接到多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18572590/

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