0

I had a problem, which I solved but I don't fully understand why the solution works:

Without the '$conn = null;' statement in the code below the number of database connections was increasing and I got a "too many database connections" error. With that statement it works fine - no increasing nr of dbase connections, but I would have assumed that the '$conn = new Database($dbname[$day]);' statement would set a new database connection, and therefore automatically close the previous one. Obvious not, but why?

for($day=0;$day<365;$day++){

  //code to determine $dbname here...
  $conn = new Database($dbname[$day]); //Database() is defined class

  //code to access database $dbname

  $conn = null; //close connection

}//for 

UPDATE: the the constructor for the Database class as requested:

public function __construct($dbname) {

    try {
        if($dbname != ECIS_DB_NAME){ //access to master database is forbidden
            $this->_db = new PDO('mysql:host='.ECIS_DB_HOST.';dbname='.$dbname, ECIS_DB_USER, ECIS_DB_PASS, array( 
            PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
        ));
            $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->_db->query('SET CHARACTER SET utf8');
            self::$count++;
        }//if
    } catch (PDOException $e) {
        exit('Error while connecting to database.'.$e->getMessage());
    }
}//public function __construct
Joppo
  • 715
  • 2
  • 12
  • 31
  • what is the code of `class Database` ? – demonking Feb 10 '14 at 08:58
  • Why do you have different databases for different days to begin with...?! – deceze Feb 10 '14 at 09:03
  • @demonking: pls see update. (I added the counter for debugging which helped me to trace the problem of increasing database connections) – Joppo Feb 10 '14 at 09:26
  • @deceze: the loop code is just a theoretical example; in the original loopcode the dbbase connection is still created and deleted in the same way.. – Joppo Feb 10 '14 at 09:29

1 Answers1

0

By unassigning $conn you are removing all references to the class and its __destruct method should be called. See "Is destructor in PHP predictable?".

The __destruct method likely has code to close the database connection. However, you should explicitly close the connection if possible, e.g.

$conn->close();
$conn = null;

If you are only connecting to a single database outside of your tests, you should initialize the database connection outside of your forloop.

Community
  • 1
  • 1
Andrew Mackrodt
  • 1,806
  • 14
  • 10