DEV Community

Pierre Bouillon
Pierre Bouillon

Posted on

PDO usage

I'm building a website and I have several SQL requests in several files.

My question is should I :

  • make a "global" PDO in a file and include the file to use it every time I need to do a request (but when close the connection?)

OR

  • create a PDO before each request and then close the connection

What will be the best practice and why?
Thanks and happy coding !

Top comments (3)

Collapse
 
sebastianr1982 profile image
Sebastian Rapetti • Edited

I prefer make a global PDO, like for your first option. Create a connection for every query is a waste of resources.

For management, if the connection isn't set as persistent, will be closed at the end of the script.

You can check official PDO PHP documentation.

Collapse
 
pbouillon profile image
Pierre Bouillon

Thanks for your answer, it's very helpful !

Collapse
 
auct profile image
auct • Edited

Usually it is used with singleton instance and is required when you need. Nowadays with autoload.
Here basic example for php phpdelusions.net/pdo/pdo_wrapper
But in every framework there is active record and/or orm.
But I always have an additional simple singleton pdo class which I use for big processing using cursor.