开发者

PHP and db connections

开发者 https://www.devze.com 2022-12-09 21:37 出处:网络
When I load a php page on my browser, it connects to the DB and runs some sql... let\'s say I now follow a link and it takes me to another page within the same website. What happened server wise? Did

When I load a php page on my browser, it connects to the DB and runs some sql... let's say I now follow a link and it takes me to another page within the same website. What happened server wise? Did my first connection to the DB close, and re-opened again? Is that what happens in mo开发者_JAVA百科st cases?


Its very likely that the connection to your database is closed once the page has been processed by PHP, obviously then the result of the PHP is sent to the browser and viewed by the user.

Assuming you're running MySQL the only reason this wouldn't be the case is if the PHP script uses mysql_pconnect, where the connection will be kept open. However its usually good practice not use use this unless the MySQL server and the PHP server have a low bandwidth connection that's unused by other processes.


Yes, in most cases your database connection will close and re-open. In particular if the PHP interpreter is restarted for each page then it has no choice but to do this.

I believe the typical exception (although I've never used this myself) is where you're using something like mod_php.so (for Apache) and you arrange for a DB connection object to be stored as part of the user's session state. I don't believe that's recommended practise, though.

See http://php.net/manual/en/features.persistent-connections.php for more.


That's the usual case yes. But if you're talking about MySQL, you can use mysql_pconnect to keep persistent connections.


It depends on how the PHP was developed. If it was coded to close after each transaction, then yes it will be re-opened each time you view a page.

There is also the concept of a database connection pool. When a connection is used it is not closed but placed into a "pool" of connections waiting to be used again. Once a specified amount of time is passed without the connection being used it is then closed to save resources.

Pooling connections saves on processing time having to reopen a connection on each page reload.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号