Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP/MySQL should I open multiple database connections or share 1?

I am wanting to hear what others think about this? Currently, I make a mysql database connection inside of a header type file that is then included in the top of every page of my site. I then can run as many queries as I want on that 1 open connection. IF the page is built from 6 files included and there is 15 different mysql queries, then they all would run on this 1 connection.

Now sometimes I see classes that make multiple connections, like 1 for each query.

Is there any benefit of using one method over the other? I think 1 connection is better then multiple but I could be wrong?

like image 638
JasonDavis Avatar asked Jan 16 '10 14:01

JasonDavis


People also ask

How many database connections do I need?

In general, the number of max connections should be equal to the number of requests you expect the web server to perform each second. This will depend on how heavy your database logic is. For a new deployment, something around 15 as the value of max connections should be OK.

Can MySQL handle multiple connections?

Simultaneous MySQL connection limitsEach database user is limited to 38 simultaneous MySQL connections. This limitation helps to prevent overloading the MySQL server to the detriment of other sites hosted on the server.

How many database connections can MySQL handle?

The thread_cache_size default value is calculated as 8 + (max_connections / 100) and is rarely changed. It might make sense to try increasing the thread cache in cases where number of connections fluctuates between having very few connections and having many connections. User Thread.

How many MySQL connections are open?

The active or total connection can be known with the help of threads_connected variable. The variable tells about the number of currently open connections. mysql> show status where `variable_name` = 'Threads_connected'; Here is the output.


2 Answers

Creating connections can be expensive (I don't have a reference for this statement as yet Edit: Aha! Here it is) so it seems as if the consensus is to use fewer connections. Using a single connection for all queries on a single page seems to be a better choice than multiple connections.

like image 182
Vincent Ramdhanie Avatar answered Oct 06 '22 11:10

Vincent Ramdhanie


In PHP+MySQL usually there is no much sence to use multiple connections per page (just slower and a little more RAM consumed).

The only way it might be useful is when you alter connection paremters which might interfer with other pages (like collation). But good PHP programs usually never do that kind of stuff.

Also, it is a good idea to enable persistent connections, so that 1 MySQL connection would be reused across multiples page executions.

like image 20
BarsMonster Avatar answered Oct 06 '22 12:10

BarsMonster