pdo连接太多,建议

时间:2016-03-09 11:50:05

标签: php mysql pdo database-connection

这是我的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; 但是,我又有太多的连接错误。我能做什么 ?

1 个答案:

答案 0 :(得分:0)

您可能应修改Config类以使用单例模式,以便它只创建一个数据库连接的实例:

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()的频率如何,都会强制使用单个数据库连接。