1

Let's say I call multiple functions on a given page.

function getProfile {
    <mysql code to connect>
    ...
    ...
}

function getMatchingUsers {
    <mysql code to connect>
    ...
    ...
}

If I call the two functions above on a given page, wouldn't that open multiple connections to the DB? I assume php would automatically close the DB connection after the first function runs, but then it would automatically open another connection for the second function. My question is, what if my page makes a bunch of calls to the DB. Is this good for memory, io, etc...?

sdot257
  • 10,046
  • 26
  • 88
  • 122

3 Answers3

1

Why not use some form of connection pooling. That way the pool maintains a set of connections, and your app is merely taking connections from the pool and returning them. The pool looks after opening and closing as required (and maintains a set of open connections).

This SO answer covers more options wrt. PHP and connection pooling.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

The simplest way is to make the connection at the beginning of your script. The mysql functions will use the last open connection to do their work, so there is no need to connect inside each function.

//Start of your file
mysql_connect()


function a(){
// no connect here, just use mysql
mysql_query($sql)
}

function b(){
// no connect here, just use mysql
mysql_query($sql)
}
Daniel Von Fange
  • 5,973
  • 3
  • 26
  • 23
0

Try to use 1 connection if you are conneciting to the same mysql server.

$host = "localhost";
$user = "user";
$pass = "password";
$database = "dbname";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");

Note that you have a $linkID and that's what you use to reference it. Make a connection specific query like this:

$resultID = mysql_query($query, $linkID) or die("Data not found.");

When you are finished, close that specific connection

mysql_close($linkID)

If you have more than 1 mysql sever addresses, then use a separate reference like $linkID2

jonycheung
  • 840
  • 1
  • 5
  • 14