Hari Dahal
Hari Dahal

Reputation: 113

MSSQL database connection from PHP (sqlsrv_close connection issue)

For database connection from PHP to MSSQL, I had create the following code. Can somebody suggest me that, is __destruct() function in my code work automatically and close the DB connection or not? Here is my code:

<?php
    class db{
        private $connection;
        private $server, $username, $password, $database, $charset;

        public function __construct($server, $username, $password, $database, $charset){
            $this->server = $server;
            $this->username = $username;
            $this->password = $password;
            $this->database = $database;
            $this->charset = $charset;

            $connectionInfo = array('UID'=>$this->username,
                                    'PWD'=>$this->password,
                                    'Database'=>$this->database,
                                    'CharacterSet'=>$this->charset);

            $this->connection = sqlsrv_connect($this->server, $connectionInfo);

            if ($this->connection === false){
                echo '<h2>Unable to connect to database</h2><br/>';
                die (print_r(sqlsrv_errors(), true));
            };
        }

        public function __destruct(){
            sqlsrv_close($this->connection);
        }

        public function query($query, $params=null){
            $result = sqlsrv_query($this->connection, $query, $params);

            if (!$result){
                echo 'Error in statement execution.\n';
                die(print_r(sqlsrv_errors(), true));
            }

            return $result;
        }
    }

Upvotes: 0

Views: 2850

Answers (1)

JamesHalsall
JamesHalsall

Reputation: 13475

Your connection will be closed, except when the __destruct method isn't called. The following scenarios cause the __destruct not to be executed:

  • If "exit" is called in another destructor
  • Depending on the PHP Version: If "exit" is called in a "register_shutdown_function" function
  • If there is a FATAL error somewhere in the code
  • If there is an exception thrown in another destructor
  • If you try to HANDLE an exception in a destructor ( PHP >= 5.3.0 )

Check this https://stackoverflow.com/a/2385581/603256

Upvotes: 1

Related Questions