Reputation: 3661
I have db
class that nearly all classes are extending:
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');
}
}
Here is page class
class page extends db {
var $common;
public function __construct() {
parent::__construct();
$this->common = new common();
And
class common extends db {
public function __construct() {
parent::__construct();
}
I'm getting
Warning: mysqli::mysqli() [mysqli.mysqli]: (42000/1203): User admin already has more than 'max_user_connections' active connections in /home/tural/public_html/incl/classes/class.db.php on line 22
How can I fix this problem?
Upvotes: 3
Views: 5502
Reputation: 2913
When you extend db class, a mysqli connection is made after each instance generation. I think it would be better if you define class db as singleton
code is the following ;
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;
}
}
By this way, you can only create 1 mysql connection.
You can reach db class by db::get_instance()->do_something();
the common class can be like this;
class page {
var $common;
var $db;
public function __construct() {
parent::__construct();
$this->db = db::get_instance();
$this->common = new common();
}
}
I think this is better design.
Upvotes: 0
Reputation: 3547
Every class inheriting from db
you instantiate establishes a new database connection. You should have just one DB class instance. All the page
and common
don't need to inherit from it, just pass them a db
instance.
Upvotes: 5