什么时候应该在PHP中关闭数据库连接? [英] When should I close a database connection in PHP?
问题描述
我与php开发人员完全不同,但我必须使用它,而且我不太了解PHP在会话期间如何处理内存分配.
I'm nothing like a php developer but I do have to use it and I'm not really aware on how PHP handle memory allocation during session.
我正在开发一个要求进行HTTP身份验证的应用程序,一旦登录,就可以通过一个漂亮的界面来操作数据.
有人在另一篇文章中告诉我,我不应该在每次执行后关闭mysql数据连接,但是我不知道在使用此应用程序期间该连接如何保持内存,因为在服务器端我不知道PHP保留了什么内容记忆与否.
I'm working on an application that ask for an HTTP authentication, once you're logged in you can manipulate data through a nice interface.
Someone told me on another post, that I shouldn't close the mysql data connection after every execution, but I don't know how this connection stay is memory during using this app because in the server side I have no idea what PHP keeps in memory or not.
所以我的问题是我应该使用单例连接到db并永远不要关闭它(因为我永远不知道何时不使用该应用程序.还是我应该坚持今天的做法:打开连接->执行语句->关闭连接.
So my question is should I use a singleton to connect to the db and never close it (because I will never know when the application is not in use. Or should I stand with what I do today: opening connection --> execute statement --> close connection.
PS:我正在使用mysqli
PS: I'm using mysqli
编辑1 :
我的应用程序是具有MVC模式含义的设计:
Edit 1:
My application is design with MVC pattern meaning :
|''''''''''| |'''''''''''''| |''''''''''''''|
| view.php | ==> | control.php | ==> | database.php |
|----------| |_____________| |______________|
该模式允许视图仅通过control.php
与数据交互,然后通过control.php
从database.php调用函数到SELECT
或EDIT
数据.加上您给我的解释,我应该输入:
That pattern allow the view to interact with data only through the control.php
which then call a function from database.php to SELECT
or EDIT
data. with the explanation you give me, I should put:
public function __destruct(){
mysql_close($this->connection);
}
在database.php
内的
内,但是当需要选择或修改数据时该页面已加载,因此它只执行很短的时间,这意味着它仍将在请求结束时关闭连接.
inside database.php
, but that page is load when there's a need to select or modify data, so it's only executed for a short time, meaning it will still close the connection at the end of the request.
哪个问题更确切地说明了我应该把您提供的代码放在何处,还是我的模式与PHP相关?
Which gives a more precise question of where should I put the peace of code you provide, or does my pattern relevant in PHP ?
推荐答案
请不要为每个查询创建新的连接.您甚至不必手动关闭它.
Never create a new connection for every query; You don't even have to close it manually.
只需在页面开头创建连接
Just create the connection at the beginning of you page
看一下:您可以使用此:
public function __destruct()
{
mysql_close($this->connection);
}
页面关闭时会被调用
这篇关于什么时候应该在PHP中关闭数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!