Frank Vilea
Frank Vilea

Reputation: 8487

How to organize the handling of database connections within functions?

When I was writing PHP code with PDO and MySQL, I would always create connections when I needed them within functions like so:

result pseudo_function() {
  create and open connection
  do stuff
  close connection
  return result
}

Now, I started programming in C, I have seen that pointers are an interesting way to pass the entire connection as parameter to the function. I was wondering if it would be better to pass the connections between functions until the entire user request is served.

To clarify: For one user request, there could be 1-5 calls to a function that then opens a database, fetches data, does something, closes and returns.

Also does it make a difference performance wise if you keep a connection opened?

Upvotes: 3

Views: 852

Answers (3)

paulsm4
paulsm4

Reputation: 121779

The "standard idiom" for most PHP code I've seen seems to be "open the connection, and leave it open".

php.net seems to be down at the moment, but these two links might be of interest:

If you're running Apache, perhaps mod_dbd might be a good solution:

Here's a good discussion on the implications of not closing your connections:

Upvotes: 3

Niko
Niko

Reputation: 26730

If you develop web applications with PHP, it's common (and I suppose the most efficient way) to open the database connection once and close it when the script terminates. Keeping a connection open while other stuff is done does not really produce any overhead or require any actions at all, but reconnecting every time does.

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173642

It's better to keep a connection open and perform 5 operations on that connection than opening a new connection every time.

You can also lazy-load your database with a singleton repository pattern; the repository only opens a connection once, upon next invocations it will return a cached result.

Upvotes: 3

Related Questions