Tell me more ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

When and how often is it good practice to start the connection to your database in php?

I'm new to databases, and I'm wondering when I should start by database connection. I'm creating a api with an index, controllers and model. Should I start the connection in the index and then pass it to all the other files, start the connection at the top of all files and call it as a global in functions as needed or start and end the connection in every function?

share|improve this question
BTW, this question is OT on Server Fault (FAQ). It might fit on Stack Overflow, put please check this site's FAQ before posting. – SvW Sep 17 '12 at 9:43
How long is a piece of string? There is not, nor can there be, a single answer to such a question, even if it was on topic. You need to examine what your code does and how, then make a determination of whether to use persistent or transient connections, or a combination of the two. – John Gardeniers Sep 17 '12 at 11:15

closed as off topic by SvW, Michael Hampton, Dan, John Gardeniers, EEAA Sep 17 '12 at 12:04

Questions on Server Fault are expected to relate to professional server, networking, or related infrastructure administration within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

1 Answer

Opening a database connections is expensive, so cycling them in every function should never be done. Instead, you open a connection at most one time during a run of your script and utilize this throughout the whole request.

In the optimal case (and mandatory for high load services), you should try to utilize persistent database connections wherever possible. This allows you to use an open connection from a previous run of the script but this is not possible in every scenario and also requires special care to make sure database operations from two script runs are properly separated.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.