Is it okay to open the database connection always?

HI, I just want to ask is it okay to have database connection open always.I have lots of function that performs like select ,insert update and deletes,and in each function I did not close the database connection.Is this okay or a bad practice ?

Thank you in advance.

If your scripts definitively end after using the connection, it’s closing itself anyway so no huge deal - but it’d be a good practice to close them.

Are you using PDO? If so, you can kill it by destroying the PDO object, or again, by script ending.

what do you mean by script end ?

Using the ‘exit’ statement, or an error, or when you reach the end of the PHP script / source code. So, there might be some scripts that run for an extremely long time - long after MySQL fetching has been needed. In that case, you’d be better closing your connections because of the extra resources you’re relegating to the unnecessary connection. If the script will end relatively quickly anyway… in my opinion it becomes semantic. I’ve seen it pointed out though, that in other languages, closing database connections is imperative, and given that, we should close them manually in PHP to develop the good coding practice. I don’t always, but… there that is.

@jemz I am not quite sure if I undersand what you mean.

In some scenarios, it is ok to have a persistent (that is, permanently open) connection to the database.

If you’re permoring lost of tasks that require manipulating data in the database so much so that the database doesn’t stay idle for more than just a few secs, then creating one persistent connection is ok.

You do need to study if this is the case, and the benefits and disadvantages of persistent connections.

You may decide that you want to close the connection after executing all those functions instead of needing a persistent connection. Then, it is a question of proper organization of the code. Maybe each function would need to check if there’s an open connection, and if it exists, use that connection and maybe an additional parameter can tell if the function should close the connection when it is finished

1 Like

It’s absolutely true that it’s an organizational issue. I’ve seen code written that had so many concurrent connections when only one was needed; and of course I’m sure the reverse of that can be true as well.

1 Like

Thank you.

I think it’s better only to open a data base connection when it’s needed and always exit() or close that connection at the end of that script it’s better practice.