gpt4 book ai didi

php - 如何修复用户 'user_name' 已超出 'max_user_connections' 资源(当前值 : 30)?

转载 作者:行者123 更新时间:2023-11-29 06:43:40 28 4
gpt4 key购买 nike

function getDB() {            
$server_name = "localhost";
$dbname = "db_name";
$user_name = "root";
$password = "12345678";

$dbConnection = new PDO("mysql:host=$server_name;dbname=$dbname",
$user_name, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbConnection->exec('SET NAMES utf8');

return $dbConnection;
}

有一些功能

function one(){
$db = getDB();

// after some mysql query

$db = null;
}

function two(){
$db = getDB();

// after some mysql query

$db = null;
}

根据要求有50多个函数调用

最佳答案

每次调用函数 getDB 时,该函数都会建立与数据库的新连接。这加起来很快。在 99,999% 的用例中,最好重用该连接。实现这一目标的一种方法是使用 static variable

function getDB() {   
static $dbConnection = null; // $dbConnection will be 'remembered', only first time it will be null

if ($dbConnection === null) {
$server_name = "localhost";
$dbname = "db_name";
$user_name = "root";
$password = "12345678";

$dbConnection = new PDO("mysql:host=$server_name;dbname=$dbname",
$user_name, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbConnection->exec('SET NAMES utf8');
}

return $dbConnection;
}

关于php - 如何修复用户 'user_name' 已超出 'max_user_connections' 资源(当前值 : 30)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50448868/

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