Reputation: 9940
I am accessing a database in a php script by establishing a connection using mysqli_connect function. I observe it is not mandatory to close the connection at the end of the script.
What are the implications of not using mysqli_close() in a connection script created to access mysql database in php?
Upvotes: 1
Views: 739
Reputation: 41508
If you're fairly sure you're not going to use the connection again, or don't have a class that manages your open connections, closing is good practice. A couple reasons:
Upvotes: 0
Reputation: 172638
If you are using cgi, then it is not necessary to close your mysql connections since they close automatically at the end of script execution.
From the documentation:
Note: The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().
Although it is considered a good practice to close your connection.
If you close the connection yourself:
- You have to check the value of
$_connected
for every single query. This means PHP has to check that the variable$_connected
A) exists B) is a boolean and C) is true/false.- You have to call your 'disconnect' function, and function calls are one of the more expensive operations in PHP. PHP has to check that your function A) exists, B) is not private/protected and C) that you provided enough arguments to your function. It also has to create a copy of the $connection variable in the new local scope.
- Then your 'disconnect' function will call mysql_close() which means PHP A) checks that mysql_close() exists and B) that you have provided all needed arguments to mysql_close() and C) that they are the correct type (mysql resource).
So if you are not using persistent connections, your MySQL connection will be closed at the end of the page execution. So you dont have to bother about that. And hence no downsides.
Upvotes: 1