我应该什么时候关闭 PHP 中的数据库连接?

2021-12-25 00:00:00 php mysql mysqli

我不像 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.

所以我的问题是我应该使用单例连接到数据库并且永​​远不要关闭它(因为我永远不会知道应用程序何时不在使用中.或者我应该坚持我今天所做的:打开连接-->执行语句 --> 关闭连接.

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 与数据交互,然后从 database.php 调用函数到 SELECTEDIT数据.根据你给我的解释,我应该说:

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

看看:你如何在 php 中有效地连接到 mysql 而无需在每次查询时重新连接

你可以使用这个:

public function __destruct()
{
   mysql_close($this->connection);
}

页面关闭时调用

相关文章