Persistent connections

software development

#1

I have seen the previous discussions on this, but they don’t answer my question.

I have a structure similar to this:

[php]
function connect() {
$s=‘some.server’; $u=‘somename’; $p=‘somepwd’; $db=‘dbname’;
$link = mysql_connect($s, $u, $p);
mysql_select_db($db, $link);
return $link;
}

function foo() {
connect(…);
//do a query
}

function bar() {
connect(…);
//do another query;
}

//some code
foo();
bar();
[/php]

How many connections are opened? The DH wiki says 2, but php.net says mysql_connect will re-use the foo’s connection in bar so only 1.

Which is correct? Running 5.3 as a fastCGI, do I have anything to gain by using mysql_pconnect instead?

Thanks in advance for any input!


#2

EDITED op to make it clear that both connections are using exactly the same criteria.


#3

There is no significant advantage to using mysql_pconnect in our PHP environment, and attempting to use it can in fact cause some odd problems.

However, mysql_connect does not reuse connections by default — indeed, it cannot, as you might actually want to select two different databases on the two handles — so your code as posted above would end up establishing two connections. Standard practice is to create a MySQL connection in the initialization code for your script or application and store the link resource in a global (or static) variable.


#4

Thanks andrewf.


#5

An update, if you’re still there andrewf?

I altered my code to check to see if a connection existed before making a new one, and if so, reuse it. I confirmed that it works as expected by monitoring the resource id’s as I used the pages in question. However, after doing so, my ratio in the mysql usage reports has dropped on average. This could have coincided with other things, but I’m going to switch back to letting php handle it, to see what happens.


#6

a lot of stuff in the panel and DH’s documentation is, unfortunately, outdated. If you search through the discussions, you’ll find that DH people such as andrewf have stated that conueries are not really used any more (http://discussion.dreamhost.com/thread-130233.html?highlight=conueries) and that their main concern is with slow queries, not necessarily the number of connections or number of queries per connection. This information should be updated because some people spend a lot of time trying to maximise that ratio but if it’s not important, they are just wasting their time…


#7

great, thanks bobocat.