简体   繁体   中英

what is the downside of not closing a mysql connection in php script?

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?

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.

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:

  1. If you're looping or something over something that creates connections without closing prior ones, you could eat up all your available DB connections based on whatever limit is set on the sql servers side. Typically this limit is for everyone not per host, so you could prevent others from connecting as well.
  2. From Zend (maybe dated): Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM