-1

Possible Duplicate:
Do I really need to do mysql_close()

Maybe the first question to ask is, do I even need to close my MySQL connections? Is this something that is done automatically at the end of each script?

Anyway, in the example below, you can see if you call DoOtherStuff() from DoStuff(), your database connection is closed before you can run the MySQL query right after the call to DoOtherStuff(). Now, what is the rule for opening and closing MySQL connections? Can I just not close any connections and open a connection whenever a function requires it? Will this create more than necessary database connections and make my code slower? Any tips for this? I'm just doing what feels best, I feel a little lost.

function DoStuff(){
    $connection = mysql_connect(...);

    DoOtherStuff();

    mysql_query(...);//This won't run

    mysql_close($connection);
}

function DoOtherStuff(){
    $connection = mysql_connect(...);

    //Does other stuff

    mysql_close($connection);
}
Community
  • 1
  • 1
sooprise
  • 22,657
  • 67
  • 188
  • 276
  • 1
    Have you tried to [read the actual manual](http://am.php.net/manual/en/function.mysql-close.php)? – lanzz Jun 14 '12 at 13:33

2 Answers2

1

No, you dont have to close your connection. As per the manual:

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Most applications only have one database connections, so actually storing the connection resource isnt needed either.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
0

Typically you open a connection once at the start of your script and either don't close it at all (which means PHP will close it at the end of the script) or you close it when you are sure you don't need it anymore.

Opening a separate connection in each function is certainly madness. You should have exactly one place in your code that says mysql_connect.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • This is what I'm struggling with. So the most ideal way to do this is the highest level code that calls everything should have the mysql_connect. Can you answer my question about what to do if you run mysql_connect multiple times? Does this cause performance issues or is PHP smart enough to handle this? – sooprise Jun 14 '12 at 14:01