I'm to developing a back-end for a demanding application that may generate a really high traffic and processing load on the server. To deal with the database connections, I came up with the following two strategies:
function connectToDB() {
return new mysqli(HOST, USR, PWD, DB);
}
function myFunction() {
$conn = connectToDB();
// do some stuff..
$conn->close();
}
The disadvantages of the preceding strategy, that I can think of, are the "so many memory allocations" and of course "many opening and closing connections". However, in the following strategy:
$conn = new mysqli(HOST, USR, PWD, DB);
function myFunction() {
global $conn;
// do some stuff..
// not closing the connection, it will be persisted to the end of the script..
}
// ...
$conn->close();
It may reach the max_connections
limit more likely than the previous method.
So, What is my way to go: to "close them immediately" or to "close them at the end of the script"? Do my concerns about the allocations or concurrent connection limits are just irrational? Or, do the strategies count at all?! Or maybe I'm completely lost in a desert of ignorance! Please shed some lights on this.
Thanks in advance :)