Reputation: 143
I'm having an issue with my database; I've been running a site for the past half year and it has been running fine since now, as it's been outputting an error when visiting it:
Database failed to connect: PDOException: SQLSTATE[08004] [1040] Too many connections in dbconfig.php:14
I've researched this quite a while but couldn't find a single solution to what may be causing this issue, as it's quite strange how it's popping up after half a year.
My connection code is like this:
class Database {
private $host = "localhost";
private $db_name = "[...]";
private $username = "[...]";
private $password = "[...]";
public $conn;
public function dbConnection() {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
exit('Database failed to connect: ' . $exception);
}
return $this->conn;
}
}
What could the issue be? I'm using this code for other sites aswell, so I hope these sites won't be having the same error soon.
Upvotes: 2
Views: 9498
Reputation: 94662
You seem to be destroying the connection unnecessariy in this code. You should be reusing the connection if it has already been made. Also if you have any open statement or results this will not actually close the connection but will open another. This could be your problem. Again it really depends upon how you use this class in your actual scripts. Repeated calls to this within the same script could be causing your problem.
So instead of that reuse it if it has already made a connection. If for no other reason than actually making a connection to tthe database is a comparatively slow process. This is often called a Singleton pattern.
class Database {
private $host = "localhost";
private $db_name = "[...]";
private $username = "[...]";
private $password = "[...]";
public $conn = null;
public function dbConnection() {
if ( $this->conn !== null ) {
// already have an open connection so lets reuse it
return $this->conn;
}
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
exit('Database failed to connect: ' . $exception);
}
return $this->conn;
}
}
Upvotes: 4