Search code examples
phpmysql-connect

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


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?

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.