gpt4 book ai didi

php - pdo连接过多,建议

转载 作者:行者123 更新时间:2023-11-29 21:16:32 25 4
gpt4 key购买 nike

这是我的 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 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() 被调用多少次,这都会强制使用单个数据库连接。

关于php - pdo连接过多,建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890820/

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