問題描述
我不像 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 調用函數到 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
看看:你如何在 php 中有效地連接到 mysql 而無需在每次查詢時重新連接
你可以使用這個:
public function __destruct()
{
mysql_close($this->connection);
}
頁面關閉時調用
這篇關于我應該什么時候關閉 PHP 中的數據庫連接?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!