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个+函数调用
答案 0 :(得分:1)
有两种可能性:
仅与您的应用程序打开1个连接。这些错误显示多个打开的连接。 1进程应该只打开1个连接,并重用它。
更改mysql配置文件,特别是https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_max_user_connections
答案 1 :(得分:1)
每次调用函数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;
}