Hi,

Which way is the best practice of opening/closing MySQL connection in PHP?

examples:

1) Making only one connection per script (one resouce)

  • open connection at the beginning of the script
  • do as many as query operations
  • close connection at the end of the script

2) Making as many as connections needed but also close them right after the query is done done (many resources)

beginning of script
...
...
...
- open connection
- do query operation(s)
- close connection right after the query
...
...
...
- open connection
- do query operation(s)
- close connection right after the query
...
...
...
- open connection
- do query operation(s)
- close connection right after the query
...
...
...
end of script

Any ideas?

    1.

    --With this choice, I am assuming the use of mysql_pconnect(), so be advised you wouldn't be able to explicitly close the connection afterwards.

      Hi,

      I'm not talking about persistent connection here.
      I have found out that using persistent connection is not a good idea since it is kept open after the script execution so that the others can use it; however, a lot of shared hosting services limit number of connections per account, so if it tries to open more than the limit, it causes an error.

      http://us2.php.net/manual/en/function.mysql-pconnect.php

        Hi,

        I'd suggest to open one connection to the database at the beginning of the script.
        It is no problem if you forget to close a connection in a script since PHP should close the connection automatically after the execution of the script when using mysql_connect.

        Thomas

          Write a Reply...