Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where and when to open a database connection

Tags:

php

mysql

I am working on implementing use of the mysql class found here in an existing script. The script almost always needs to interact with the database, even if there are times when it does not. What is the best practice in this case? Should I open a connection and keep that open until the end of the script or should I open a connection when I need one, closing it when I'm done, to avoid opening a connection when the script does not need it?

like image 582
Felix Andersen Avatar asked Jul 14 '09 16:07

Felix Andersen


2 Answers

Because connections are rather expensive, as others have pointed out, I'd recommend using a "lazy connect" technique in your database layer. If you have structured your application effectively, your application logic should not be concerned with when connections are opened and closed as this would be encapsulated in the database layer. The database layer, when asked to perform a query, would first check to see if it has an active connection and if not, create one. This way you'll avoid opening connections that are never used and you'll also have a nice separation of logic between your application and the database code.

like image 200
pix0r Avatar answered Oct 29 '22 01:10

pix0r


Well, if you are using a class, the connection should be opened automatically when you instantiate the class, or when the first query is performed. If you never use the class, the connection wouldn't be opened. While it is good practice to close it when you don't need it, it doesn't hurt to let it be closed when the request thread dies.

This can be bad if you don't have a resource limits set in your php.ini file, the request could possible live forever and never close the connection.

If you have a medium-to-high traffic site, you should be thinking about using mysql_pconnect anyways so there is always a connection open and you don't need the overhead of opening one on every request.

like image 25
Byron Whitlock Avatar answered Oct 29 '22 00:10

Byron Whitlock