Search code examples
phpmysqldatabase-connection

Does php always need to connect?


Normally SQL in php always need to execute mysql_connect before doing queries while viewer is opening .php file. Is there a way to connect one time and call php file multiple times without new connection? I would use it to reduce accessing time because script is connecting to remote MySQL server.


Solution

  • Does php always need to connect?

    Yes.

    Is there a way to connect one time and call php file multiple times without new connection?

    In stock PHP - no.

    Because PHP is tied closely to the stateless CGI model (even when used as an Apache module, FastCGI process, or ISAPI extension). Under this classic CGI model the process that created the page response is terminated immediately so any database connections made would be closed.

    In practice this is not a problem as RDBMSs like MySQL are designed so that opening a new connections is a very quick process (as long as the MySQL server is within a short ping distance of the webserver). Other systems like MSSQL (especially under ASP.NET) make use of "connection pooling" where the actual underlying connection is maintained by the OS or the host process.