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;
}
}
Your connection will be closed, except when the
__destructmethod isn’t called. The following scenarios cause the__destructnot to be executed:Check this https://stackoverflow.com/a/2385581/603256