I have a basic HTML file, using jQuery's ajax, that is connecting to my polling.php script every 2 seconds.
The polling.php simply connections to mysql, checks for ID's newer than my hidden, stored current ID, and then echo's if there is anything new. Since the javascript is connecting every 2 seconds, I am getting thousands of connections in TIME_WAIT, just for my client. This is because my script is re-connecting to MySQL over and over again. I have tried mysql_pconnect but it didn't help any.
Is there any way I can get PHP to open 1 connection, and continue to query using it? Instead of reconnecting every single time and making all these TIME_WAIT connections. Unsure what to do here to make this work properly.
No, it is not possible. There is no way for php to open only one connection, because every request to HTTP server is passed to worker process, which execute php script (and create new connection).
If your MySQL and HTTP server are running on same server, you could use unix socket connection instead of TCP connection.
You colud adjust
net.ipv4.netfilter.ip_conntrack_tcp_timeout_time_wait
kernel parameter, to reduce number of connections inTIME_WAIT
state.You can connect to MySQL via unix domain sockets instead, given PHP server and MySQL server are on the same server. Here are some hints how to switch to domain sockets:
MacPorts, MySQL, PHP5 and that socket thing ..
If you have separate servers you may want to find out more about connection pooling. The most simplistic approach to get started seems to be using
mysql_pconnect
instead ofmysql_connect
. (p for persistent)