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

时间:2018-05-21 12:24:46

标签: php mysql

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个+函数调用

2 个答案:

答案 0 :(得分:1)

有两种可能性:

答案 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;
}