When issuing a MySQL/SQL query from PHP code, a connection with the database must be firstly established.
Would you advise me, please, whether I should establish connection with the database only at the beginning of the user’s web session, or upon loading new page, or before every single MySQL/SQL query?
I think that when establishing connection with the database too many times unnecessarily, I will consume unnecessary system resources. I would therefore prefer connecting with the database the minimum necessary times.
You need to strike the right balance. Each part has its problems. Let’s go over all three possibilities
Persistent MySQL connection
Advantages: load-once-and-forget
Disadvantages: you’ll need to make sure to kill any connection that is not active anymore yourself. Also, a dormant connection still uses some resources. Not recommended, as the only good case for it is a lot of requests, at which point you’ll most likely want to cluster up your database servers, and persistent connections tend to play havoc with that.
One-query-one-request model
Advantages: build-and-forget
Disadvantages: extreme resource usage.
The good solution is a right balance. Load up your DBH when you actually need it for the first time, and keep it until your script is over, at which point you should free all resources used by it and terminate it. This guarantees that you’ll have done everything using the minimum amount of resources needed.