Should I connect to a database once in a constructor or within each method that works with a database?

StackOverflow https://stackoverflow.com/questions/11396287

  •  19-06-2021
  •  | 
  •  

Question

I have a class that contains three methods:

  • insert
  • update
  • delete

Each of these methods works with a database. Which is a better method?

  1. Connect to the database in the constructor and close the connection in the destructor, or
  2. Open and close a connection in each method separately?
Was it helpful?

Solution

You only have to connect once which you will want to do before you call the methods.

You will have to connect before the methods and then execute your mysql queries inside each method.

You can disconnect after you call the methods if you feel the need, but it is generally unnecessary to close the connection as it closes automatically after the page loads.

OTHER TIPS

It depends on the use-case. But in 99% of all cases you would open the connection in your constructor. (Nevermind the destructor. PHP destroys the connection on script-end if its not a persistent connection.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top