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 !

Did you find this post useful? Show some love!
DISCUSSION (3)

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.

Thanks for your answer, it's very helpful !

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.

Classic DEV Post from Jul 3

Can't get engineering interviews? Try the side door.

If you're struggling to get engineering interviews at startups, consider trying other ways to get your foot in the door. Do more than just submit an application.

Pierre Bouillon
Developer, student, tech enthusiast and coffee junky. I would be glad to speak with you!
Join dev.to ❀️

The heartbeat of the software industry.