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 12

What newsletters are you subscribed to?

I'm just curious which newsletters people on here are subscribed to, both work ...

READ POST
Follow @citizen428 to see more of their posts in your feed.
Pierre Bouillon
Developer, student, tech enthusiast and coffee junky. I would be glad to speak with you!
More from @pbouillon
Explain me C compilation like I'm five
#explainlikeimfive #beginners #c #discuss
MinGW pronunciation
#discuss #beginners #funny
Trending on dev.to
Lessons I learned from training with special forces that I use in software development
#beginners #career #motivation #dieliving
PHP Security: Introduction
#php #security
How To Put Arrows at the Bottom of a Div
#webdev #beginners #html #css
My journey from PHP to Go
#php #go #feedback
The Ultimate CSS3 Property List
#webdev #css #webdesign
PHP Security: Passwords
#php #security #cryptography
Demystifying Webpack
#webdev #frontend #backend #javascript
Building My First Sinatra-based Ruby App: Thoughts and Wrap-up
#sinatra #ruby #beginners