-2

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?
Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
Wizard
  • 10,985
  • 38
  • 91
  • 165
  • 1
    Sorry, but may be U will use frameworks? Or U just interesting to write new bycicle? – Sergey Jul 09 '12 at 13:45
  • 2
    Connect once and leave it open. Establishing the connection is an expensive process and a connection can be reused in the script as many times as needed. – Michael Berkowski Jul 09 '12 at 13:45
  • @Sergey this is small project, i think that I don't need framework – Wizard Jul 09 '12 at 13:47
  • @TomasLietuva, check out http://codeigniter.com its light weight, and saves you TIME on making DB connections and securing input, it just works. No point to write boilerplate code for even the smallest of projects when you can utilize a light framework. – Jakub Jul 09 '12 at 13:50
  • 2
    @TomasLietuva, if you ask such question, it is probably because you actually **need** a framework, you're a trying to solve a common problem, and there are tons of people who already solved it before, a framework is not only Zend or Symfony, it may be only Doctrine DBAL and/or ORM, Pear:DB, etc.. If you really don't need this, then use native PDO and/or PHP mysql_* functions. – Boris Guéry Jul 09 '12 at 13:50

2 Answers2

4

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.

Max Hudson
  • 9,961
  • 14
  • 57
  • 107
1

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.)

Ron
  • 1,336
  • 12
  • 20