[英]How to create 2 PDO database connection instances PHP
我目前有一個創建一個數據庫連接的類,但是我也想創建另一個連接。 我曾嘗試復制類結構,但只是重命名變量和函數,但是這種方法不起作用,而且當我收到錯誤消息時,它似乎無法檢測到新的PDO連接的位置Uncaught Error: Call to a member function prepare() on null in
。 在我的情況下,創建2個數據庫連接時最好的方法是什么?
config.php文件:
<?php
class Database
{
private $host = "localhost";
private $db_name = "database1";
private $username = "root";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
class.user.php:
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
您可以創建User類,並將連接傳遞給構造函數。 這將使您靈活地換出連接。
關於數據庫類,它似乎是創建PDO連接的包裝器。 您可以取消它,或者使用不同的參數擴展類。
也許看看依賴注入和容器。 他們可能會在這里為您提供幫助。
<?php
class User
{
private $conn;
public function __construct(PDO $conn)
{
$this->conn = $conn;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.