pdo连接太多,建议

pdo too many connection, suggestion

这是我的 php 代码。问题是数据库连接和数据库关闭。我有太多的连接错误。我使用 $db = null; 但我又遇到了错误。我能做什么? 谢谢...

db.php

    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name .";charset=utf8", $this->username, $this->password); 
        }

        catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}


$database = new Config();
$db = $database->getConnection();

data.inc.php

include 'db.php';

private $table_name = "contents";

public function __construct($db){
        $this->conn = $db;      
    }

function dbclose() { 

    $this->conn = null;

    return true;
    }

      function readContents($page, $from_record_num, $records_per_page,$category){


            $query = "SELECT 
                    *
                FROM 
                    " . $this->table_name . " where cat_id = ?
                ORDER BY 
                date desc 
                LIMIT 
                    {$from_record_num}, {$records_per_page}";

        $stmt = $this->conn->prepare( $query );
        $stmt->bindParam(1, $cat_id);
        $stmt->execute();

        return $stmt;
    }

index.php

    $stmt1 = $product->readContents(1, 0, 20, 1); //page,0,20 list contents,category 1
    $stmt2 = $product->readContents(1, 0, 20, 5); //page,0,20 list contents,category 5
    $stmt3 = $product->readContents(1, 0, 20, 13); //page,0,20 list contents,category 13

while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)){ //20 contents in category 1 }
while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)){ //20 contents in category 5 }
while ($row3 = $stmt3->fetch(PDO::FETCH_ASSOC)){ //20 contents in category 13 }

$product->dbclose();

我使用了 $db null; 但是,我又遇到了太多的连接错误。我能做什么 ?

也许您应该修改 Config class 以使用单例模式,以便它只创建一个数据库连接实例:

class Config {
    static $conn = false;

    public function getConnection(){

      if(static::$conn === false) {
        // no db connection established: create one
        try{
            static::$conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name .";charset=utf8", $this->username, $this->password); 
        }

        catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
      }

      return static::$conn;
    }
}

无论调用 getConnection() 的频率如何,这都会强制使用单个数据库连接。