Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of opening MySQL connections over and over again in PHP

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?

like image 692
SwampWater Avatar asked Dec 16 '22 23:12

SwampWater


2 Answers

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:

http://www.google.com/webhp?hl=&sourceid=navclient-ff&rlz=1B3GGLL_enUS384US384&ie=UTF-8#rlz=1B3GGLL_enUS384US384&hl=en&source=hp&q=mysql+persistent+connection&aq=0&aqi=g4g-m5&aql=&oq=mysql+persistent+conn&gs_rfai=Ch2c6iCchTO3zG4i6MZ-i7JAOAAAAqgQFT9BAKCs&fp=ff274912d96214e6

-- HTH

like image 151
Pete Wilson Avatar answered Dec 30 '22 11:12

Pete Wilson


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

like image 35
Nik Chankov Avatar answered Dec 30 '22 11:12

Nik Chankov