I am working on a website which is very MySQL DB driven. So I have a lot of queries going on.
In this topic everyone recommends to connect to the DB at the top of the page, and disconnect at the bottom of the page.
I am wondering what's more efficient, or generally speaking best practice: Make a single db connection per page, or only connect as needed? (Or is there no general answer, and it depends?)
Additionally I am looking to find out WHY is this best practice, from which point of view are you looking at the scenario (e.g. security, speed, ... I don't know what else DB connections might affect?!)
I believe this question has been asked before here - but not for PHP in specific, and therefore I didn't find it helpful.
My current practice has been to connect to the DB per mysqli for each function I write, and disconnect at the end of the function, because it seemed cleaner to me. This way, if a page doesn't call to a function which requires DB access, there will never be a connection opened. However it may happen, that there might be up to approximately 10 connections per page load, depending on what the user does on the site. Now I thought this might be a fair distribution of resources. If I understood it correctly there can only always be 1 DB connection opened. Therefore I assume all connection requests will be queued. So if a user has multiple, long and complicated queries, this user would not hold up all traffic, because in between each of the queries, other short queries could get processed. But that's just me making stuff up, I don't know if it would really work that way... :D
Also I know that a lot of developers around here like to use PDO. I chose to use mysqli when I started developing, and I have no plans of switching. I hope my question can be applicable to both libraries.
Thanks :-)