【问题标题】:User already has more than 'max_user_connections' active connections用户已经有超过 'max_user_connections' 个活动连接
【发布时间】:2012-07-01 22:53:22
【问题描述】:

我有 db 几乎所有类都在扩展的类:

class db {

    protected $db;

    public function __construct() {
        $this->connect();
    }

    protected function connect() {
        $this->db = new MySQLi(db_host, db_user, db_pass, db_name) or die($this->db->error); (line 22)
        $this->db->set_charset('utf8');
    }

}

这是页面类

class page extends db {
    var $common;

    public function __construct() {
        parent::__construct();
        $this->common = new common();

class common extends db {

    public function __construct() {
       parent::__construct();
    }

我来了

警告:mysqli::mysqli() [mysqli.mysqli]: (42000/1203): 用户管理员 已经有超过 'max_user_connections' 的活动连接 /home/tural/public_html/incl/classes/class.db.php 第 22 行

我该如何解决这个问题?

【问题讨论】:

  • 您是否关闭或共享连接?
  • @Ben no...如何从另一个班级关闭它?
  • 对不起,mysqli 不是我的专长;我相信很快就会有人来。在其他语言中,连接对象也将具有disconnect 函数。

标签: php mysql database mysqli


【解决方案1】:

从您实例化的db 继承的每个类都会建立一个新的数据库连接。您应该只有一个数据库类实例。所有pagecommon 都不需要继承它,只需传递一个db 实例即可。

【讨论】:

    【解决方案2】:

    当您扩展 db 类时,每次生成实例后都会建立一个 mysqli 连接。我认为如果将类 db 定义为单例会更好

    代码如下;

    class db {
    
        private static $_db; // db instance
        protected $connection;
    
        private function __construct() {
            $this->connection = new MySQLi(db_host, db_user, db_pass, db_name) or die($this->connection->error); 
            $this->connection->set_charset('utf8');
        }
    
        public function get_instance()
        {
            if( isset( self::$_db) )
            {
               return self::$_db;
            }
            else
            {
               self::$_db = new db();            
            }
    
            return self::$_db;
        }
    
    }
    

    这样,你只能创建1个mysql连接。

    您可以通过db::get_instance()->do_something();访问db类

    普通类可以这样;

    class page  {
        var $common;
        var $db;    
    
        public function __construct() {
            parent::__construct();
            $this->db = db::get_instance();
            $this->common = new common();
        }
    }
    

    我认为这是更好的设计。

    【讨论】:

    • 那么,您建议删除所有扩展?为什么$this->db = db::get_instance(); 不是$this->db = new db();
    • 为什么 $this->db = db::get_instance();不是 $this->db = new db(); ?
    • 在单例模式中,对象类型始终是静态的。因此,实例返回被自动处理,以确保该 db 对象仅存在 1 个实例。请注意,在此示例中,__construct() 是私有的,因此您不能使用 new 语句。
    • 收到此错误消息:) 解析错误:语法错误,意外 ')',期待 '(' 在线 if (isset(self::_db))
    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 2014-05-20
    • 2014-06-14
    • 1970-01-01
    • 2011-05-04
    • 2010-10-21
    • 2016-08-01
    相关资源
    最近更新 更多