Reputation: 257
Specifically, I have a DB class that opens and closes multiple MySQL connections every time I call the Query function in the class. Should I open a connection once? or is it ok to open and close connections like this?
Upvotes: 4
Views: 824
Reputation: 5931
I think you should use a Registry Object to open your Database Connection, and make your Database Object a singleton.
Registry::Set('DB', new Database());
$DB = Registry::Get('DB');
Upvotes: 0
Reputation: 37655
In general, go back to the simplest MySQL tutorial you can find and do it just that way. Don't deviate unless you have a problem you are trying to solve.
MySQL works just fine when you keep it brain-dead simple. Don't add complexity.
BTW, are you writing yet another MySQL abstraction layer? Why? This question is a good example why reinventing a wheel can be risky.
Upvotes: 1
Reputation: 182
conecting also uses cpu time. so if you reconnect about 8 times per page, and you have somewhat about 100 visitors a day wich call up 5 pages in average you have 8*100*5=4000 reconnects in one day. and thats a small website. you should realy think about connecting only once or when the connection is getting lost. that would somehow lower your electricity bill also ;-)
Upvotes: 0
Reputation: 8694
My simple-minded (ISAM, no transactions) C-language app runs for eight hours a day, updating multiple tables in one database over one single MySQL connection that stays open the whole time. It works just fine. Anytime there's any kind of MySQL error (not only server gone away), the code just calls mysql_real_connect() again and it picks right up without any trouble. Reconnection is one of the places where, in my opinion, MySQL functions flawlessly.
But there's plenty of controversy and discussion about the goodness/badness of persistent connections. You can find some of it here:
-- HTH
Upvotes: 3
Reputation: 157895
Should I open a connection once?
No.
I thought it would be better to release the memory
Actually, connect itself do not consume memory.
And - most important part - you should not worry of such imaginable things.
Don't make decisions on based on empty assumptions.
Here is 2 simple rules to follow:
Upvotes: 3
Reputation: 6047
If you don't want to change much instead of mysql_connect() use mysql_pconnect() This way you will use the opened connection. Bu I would agree with @Sarfraz Ahmed - use it only once
Upvotes: 3
Reputation: 382696
Should I open a connection once? or is it ok to open and close connections like this?
You should open multiple connection only when needed otherwise it is not a good idea to open multiple connections thereby consuming a lot of memory which is an overhead.
Upvotes: 2