简体   繁体   English

如何创建2个PDO数据库连接实例PHP

[英]How to create 2 PDO database connection instances PHP

I currently have a class which creates one database connection, however I would like to create another connection too. 我目前有一个创建一个数据库连接的类,但是我也想创建另一个连接。 I have tried copying the class structure but just renaming the variables and functions however that doesn't work and it seems like it doesn't detect where my new PDO connection is as I get error Uncaught Error: Call to a member function prepare() on null in . 我曾尝试复制类结构,但只是重命名变量和函数,但是这种方法不起作用,而且当我收到错误消息时,它似乎无法检测到新的PDO连接的位置Uncaught Error: Call to a member function prepare() on null in What is the best approach to take in my case when creating 2 database connections? 在我的情况下,创建2个数据库连接时最好的方法是什么?

config.php: 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.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;
    }
}

You could create your User class and pass the connection to the constructor. 您可以创建User类,并将连接传递给构造函数。 This will give you flexibility to swap out the connection. 这将使您灵活地换出连接。

Regarding your database class, it seems to be a wrapper, to create a PDO connection. 关于数据库类,它似乎是创建PDO连接的包装器。 You could do away with it, or extend the class with different params. 您可以取消它,或者使用不同的参数扩展类。

Perhaps look at dependency injection, and containers. 也许看看依赖注入和容器。 They might help you here. 他们可能会在这里为您提供帮助。

<?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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM