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!

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 Feb 26

Self-Deprecation Needs to 🛑

My thoughts on self-deprecation in tech.

READ POST
Follow @mauricehayward to see more of their posts in your feed.
Pierre Bouillon
Developer, student, tech enthusiast and coffee junky.
More from @pbouillon
Explain me C compilation like I'm five
#explainlikeimfive #beginners #c #discuss
MinGW pronunciation
#discuss #beginners #funny
Trending on dev.to
Would Socrates Use Docker Today?
#docker #beginners #learning #productivity
How to use Ansible
#ansible #python #php #beginners
Install Laravel
#beginners #php #laravel
Building AR/VR with Javascript and HTML
#augmentedreality #javascript #virtualreality #webdev
How to create a Hacker News API GraphQL data source for GatsbyJS
#gatsby #webdev #javascript
Why homogenous dev setups aren't the best idea
#webdev #performance
Introducing JavaScript Objects
#beginners #javascript #webdev
Sails.js is a Node.js MVC framework inspired by Ruby on Rails
#mvc #webdev #javascript #node