tags:

views:

918

answers:

3

At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP?

$mysqli = new mysqli("localhost", "root", "", "test");
...do stuff, perhaps redirect to another page...
$mysqli->close();
+13  A: 

From: http://us3.php.net/manual/en/mysqli.close.php

"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."

David McLaughlin
+2  A: 

There might be a limit of how many connections can be open at once, so if you have many user you might run out of SQL connections. In effect, users will see SQL errors instead of nice web pages.

It's better to open a connection to read data, then close it, then display data and once the user clicks "submit" you open another connection and then submit all changes.

steffenj
"In effect, users will see SQL errors instead of nice web pages." - I hope not display_errors = 0;!
Ross
+3  A: 

Just because you redirect doesn't mean the script stops executing. A redirect is just a header being sent. If you don't exit() right after, the rest of your script will continue running. When the script does finish running, it will close off all open connections (or release them back to the pool if you're using persistent connections). Don't worry about it.